How to avoid .pyc files?

2019-01-01 11:50发布

Can I run the python interpreter without generating the compiled .pyc files?

9条回答
情到深处是孤独
2楼-- · 2019-01-01 12:26
import sys

sys.dont_write_bytecode = True
查看更多
不再属于我。
3楼-- · 2019-01-01 12:28

In 2.5, theres no way to suppress it, other than measures like not giving users write access to the directory.

In python 2.6 and 3.0 however, there may be a setting in the sys module called "dont_write_bytecode" that can be set to suppress this. This can also be set by passing the "-B" option, or setting the environment variable "PYTHONDONTWRITEBYTECODE"

查看更多
与君花间醉酒
4楼-- · 2019-01-01 12:29

I have several test cases in a test suite and before I was running the test suite in the Mac Terminal like this:

python LoginSuite.py

Running the command this way my directory was being populated with .pyc files. I tried the below stated method and it solved the issue:

python -B LoginSuite.py

This method works if you are importing test cases into the test suite and running the suite on the command line.

查看更多
谁念西风独自凉
5楼-- · 2019-01-01 12:30

As far as I know python will compile all modules you "import". However python will NOT compile a python script run using: "python script.py" (it will however compile any modules that the script imports).

The real questions is why you don't want python to compile the modules? You could probably automate a way of cleaning these up if they are getting in the way.

查看更多
路过你的时光
6楼-- · 2019-01-01 12:31

You can set sys.dont_write_bytecode = True in your source, but that would have to be in the first python file loaded. If you execute python somefile.py then you will not get somefile.pyc.

When you install a utility using setup.py and entry_points= you will have set sys.dont_write_bytecode in the startup script. So you cannot rely on the "default" startup script generated by setuptools.

If you start Python with python file as argument yourself you can specify -B:

python -B somefile.py

somefile.pyc would not be generated anyway, but no .pyc files for other files imported too.

If you have some utility myutil and you cannot change that, it will not pass -B to the python interpreter. Just start it by setting the environment variable PYTHONDONTWRITEBYTECODE:

PYTHONDONTWRITEBYTECODE=x myutil
查看更多
笑指拈花
7楼-- · 2019-01-01 12:36

Solution for ipython 6.2.1 using python 3.5.2 (Tested on Ubuntu 16.04 and Windows 10):

Ipython doesn’t respect %env PYTHONDONTWRITEBYTECODE =1 if set in the ipython interpretor or during startup in ~/.ipython/profile-default/startup/00-startup.ipy. Instead using the following in your ~.ipython/profile-default/startup/00-startup.py

import sys
Sys.dont_write_bytecode=True
查看更多
登录 后发表回答