Reputation: 1353
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.
Upvotes: 0
Views: 132
Reputation: 365717
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.
Upvotes: 1
Reputation: 601609
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.
Upvotes: 3