Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to have compiled python files in a separate folder?

Is it possible to have Python save the .pyc files to a separate folder location that is in sys.path?

/code     foo.py     foo.pyc     bar.py     bar.pyc 

To:

/code    foo.py    bar.py /code_compiled    foo.pyc    bar.pyc 

I would like this because I feel it'd be more organized. Thanks for any help you can give me.

like image 776
Evan Fosmark Avatar asked Jan 23 '09 05:01

Evan Fosmark


People also ask

Where do compiled Python files go?

Basically all python files will be compiled to directory __pythoncache__ . jb. jb.

How do you compile all files in Python?

Using compileall. compile_dir() function: It compiles every single python file present in the directory supplied. Using py_compile in Terminal: $ python -m py_compile File1.py File2.py File3.py ...


1 Answers

Update:

In Python 3.8 -X pycache_prefix=PATH command-line option enables writing .pyc files to a parallel tree rooted at the given directory instead of to the code tree. See $PYTHONPYCACHEPREFIX envvarcredits: @RobertT' answer

The location of the cache is reported in sys.pycache_prefix (None indicates the default location in __pycache__ [since Python 3.2] subdirectories).

To turn off caching the compiled Python bytecode, -B may be set, then Python won’t try to write .pyc files on the import of source modules. See $PYTHONDONTWRITEBYTECODE envvarcredits: @Maleev's answer


Old [Python 2] answer:

There is PEP 304: Controlling Generation of Bytecode Files. Its status is Withdrawn and corresponding patch rejected. Therefore there might be no direct way to do it.

If you don't need source code then you may just delete *.py files. *.pyc files can be used as is or packed in an egg.

like image 194
jfs Avatar answered Oct 15 '22 18:10

jfs