简体   繁体   中英

How to compile python code for 2.x from 3.x

I want to compile python code for target 2.7 from a 3.2 script.

Below works fine for compiling. But on execution I obviously get a "Bad magic number error" because compile & target python versions are different.

for fn in os.listdir(source):
    srcfile = ...
    ...
    destfile = ... + ".pyc"
    #print(srcfile, destfile)
    py_compile.compile(srcfile, destfile)   # <-- 

Is it possible without executing 2.7 python from within 3.2? Is there a way to mention target version?

Thanks.

The CPython binary can't cross-compile for a different Python version. You are probably best off by forking out to a Python interpreter with the desired target version and using the compileall module directly from the command-line.

The compile function, modules like compileall and ast , etc. all just expose the parser and compiler that are baked into each Python version. Python 3.2 doesn't have a compiler for 2.7 code.

And if you were expecting to compile 3.2 code into 2.7 bytecode… that's not even possible, in general, so obviously Python 3.2 can't do it.

You could try to port all of the 2.7 compiler machinery to Python—PyPy would be a good source to start from—and then run that under 3.2. But that's a lot of work just to avoid installing Python 2.7 alongside 3.2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM