As the comments pointed out, exec() uses the current python implementation, so you can't execute python 2 code from python 3 using it.
Unless you port it, your best bet is simply to call it as a subprocess, using either os.system..:
./py3.py
#!/usr/bin/env python3
import os
print('running py2')
os.system('./py2.py')
print('done')
./py2.py
#!/usr/bin/env python2.7
print "hello from python2!"
Then (after making them both executable) run:
$ ./py3.py
Or alternatively you can use the more flexible subprocess, which allows you to pass data back and forward more easily using a serialising module such as json so that you can get your results from the python2 script in your python3 code:
./py3.py
#!/usr/bin/env python3
import json
from subprocess import PIPE, Popen
print('running py2')
py2_proc = Popen(['./py2.py'], stdout=PIPE)
# do not care about stderr
stdout, _ = py2_proc.communicate()
result = json.loads(stdout.decode())
print('value1 was %s, value2 was %s' % (result['value1'], result['value2']))
./py2.py
#!/usr/bin/env python2.7
import json
my_result = {
'value1': 1,
'value2': 3
}
print json.dumps(my_result)
Like that it may be easy to pack up the data you need and transport it over.
Note: I have used a very simple environment setup here using my system's python2.7 and python3. In the real world the most painful thing about getting this sort of thing to work properly is configuring the environment correctly. Perhaps, e.g., you are using virtual environments. Perhaps you are running as a user which doesn't have the right python2 version in their path. Perhaps you can't make the files executable and so have to specify the path to python in your subprocess / os.system call. There are many options and it is very complicated, but out of the scope of the question. You just have to read the doc pages very carefully and try a few things out!
os.system('python python2script.py')? This is equivalent to issuing the command that's in quotes on the command line.execwill naturally execute everything that it receives in the current (python 3) interpreter.os.systemdoes not work, then you could look at rewriting the python2 script to use__future__imports and more python3-friendly syntax. However, exec(open(python2file).read()) is an extremely clunky way to do this. The preferred method is toimport python2fileand run its code.os.system('script.py')