Can compiled bytecode files (.pyc) get generated in different directory? [duplicate]

北城以北 提交于 2019-11-29 09:15:35
mikl

This is answered in "Way to have compiled python files in a seperate folder?"

Short answer: No – unless you're running Python 3.2 or later – see here.

To clarify: Before 3.2, you can compile bytecode and put it elsewhere as per Brian R. Bondy's suggestion, but unless you actually run it from there (and not from the folder you want to keep pristine) Python will still output bytecode where the .py files are.

Check the py_compile module, and in particular:

py_compile.compile(file[, cfile[, dfile[, doraise]]])

The cfile is the parameter you are interested in.

From the link above:

...The byte-code is written to cfile, which defaults to file + 'c'...

I was looking for an answer to this myself, and couldn't find too much. However you can just prefix the folder name to the newly compiled file name (need to make sure folder exists first)

Here's some code that works for me:

import py_compile
import os
import glob
import shutil

path = ''
for infile in glob.glob( os.path.join(path, '*.py') ):
    print "current file is: " + infile
    strDestination = 'compiled/' + infile + 'c'
    py_compile.compile(infile,strDestination)

In case the "littering" indeed is your problem, you can always pack .py, .pyc and/or .pyo files in a .zip file and append it to your sys.path.

I seem to remember reading somewhere that this is not possible and that the Python People have reasons for not making it possible, although I can't remember where.

EDIT: sorry, I misread the question - what I meant is that it's not possible (I think) to configure the Python executable to put its bytecode files in a different directory by default. You could always write a little Python compiler script (or find one, I'm sure they're out there) that would put the bytecode files in a location of your choosing.

samoz

You could write a script to compile them and then move them around. Something like:

for i in `ls *.pyc`
do
 mv $i $DEST_DIR
done

(which can be shortened to:

for i in *.pyc
do
    mv $i $DEST_DIR
done

or, surprisingly, to

mv *.pyc $DEST_DIR

)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!