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
  • 24,226
  • 19
  • 100
  • 173

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
  • 25,364
  • 9
  • 55
  • 65
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
  • 24,226
  • 19
  • 100
  • 173
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
  • 86,894
  • 26
  • 169
  • 240
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
  • 89,107
  • 13
  • 149
  • 217
  • 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