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
有帮助吗?

解决方案 3

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:

其他提示

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.

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)

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top