8

Is there a way to stop python from creating .pyc files, already in the shebang (or magic number if you will) of the Python script?

Not working:

#!/usr/bin/env python -B
Prof. Falken
  • 23,276
  • 18
  • 98
  • 168

4 Answers4

7

it is possible by putting your python interperter path directly in the she bang instead of using env.

#!/usr/bin/python -B

of course this means you lose out on some of the portability benefits of using env. There is a discussion of this issue with env on the wikipedia Shebang page. They use python as one of their env examples.

Marwan Alsabbagh
  • 23,628
  • 9
  • 50
  • 63
4

Yes, if and only if, we assume the Python program runs in a somewhat POSIX compatible system (for /bin/sh), this will work:

(IMPROVED based on input from glglgl)

#!/bin/sh
"exec" "python" "-B" "$0" "$@"

# The rest of the Python program follows below:
Prof. Falken
  • 23,276
  • 18
  • 98
  • 168
4

According to the man page for env, you can pass name=value to set environment variables. The PYTHONDONTWRITEBYTECODE environment variable causes Python to not write .py[co] files (the same as the -B flag to python). So using

#!/usr/bin/env PYTHONDONTWRITEBYTECODE=1 python

should do the trick.

EDIT:

I tested this with a simple Python script:

#!/usr/bin/env PYTHONDONTWRITEBYTECODE=1 python
print 1

then

$chmod +x test.py
$./test.py
1
$ls
test.py

(but not test.pyc)

asmeurer
  • 80,291
  • 25
  • 162
  • 229
3

Alas, no. The shebang stuff is limited to giving an executable and one parameter.

So env tries to execute python -B with the given file as one argument instead of python with -B and the current file as two arguments.

I don't see a way to achieve the wanted goal.

glglgl
  • 85,390
  • 12
  • 140
  • 213
  • 2
    The funny part is that Python Windows Launcher doesn't know about this limitation and passes the options (un)correctly. So for once Python on Window works better ;) – lqc Nov 14 '12 at 11:48