views:

643

answers:

5

When python compiles modules to bytecode, it produces .pyc files from your .py files.

My question is, is it possible to have these .pyc files written to a different directory than where the module resides?

For example, I have a large directory of modules. Rather than having it littered with .pyc files, I would like to keep my source code in the directory and have a subdirectory like "bytecode" where all of the .pyc are stored.

Is this possible?

A: 

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.

David Zaslavsky
+3  A: 

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'...

Brian R. Bondy
A: 

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

)

samoz
I added two more versions of your code, although I believe its functionality is equivalent to `rm *.pyc`: the compiled files can be moved; so what?
ΤΖΩΤΖΙΟΥ
+8  A: 

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

Short story: No.

To clarify: 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.

mikl
+2  A: 

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.

ΤΖΩΤΖΙΟΥ