简体   繁体   中英

exec() python2 script from python3

I would like to know if it is possible to execute a python2 script from a python3 script.

I have a file written using py3 that must execute legacy code written in py2 to obtain dictionaries for processing within the initial file.

The line in py3 to call the mentioned py2 script is

exec(open('python2script.py').read())

The script runs without error until it begins processing python2script.py , at which point it crashes at the first difference with version3.

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, eg, 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!

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