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

StackOverflow https://stackoverflow.com/questions/611967

  •  03-07-2019
  •  | 
  •  

Question

Possible Duplicate:
Way to have compiled python files in a separate folder?

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top