简体   繁体   中英

Use two separate versions of python in the same script

I have two blocks of code that I would like to combine into one python script. One block of code is written in Python 2.7, the other in Python 3.6

My question is, is there some way to call an old version of python mid script to run that specific block of code?

For instance, if I ran the following code, the script would error out because the second print statement is missing the parenthesis:

#Running python 2 and 3!!

#Py 2
print "Python 2"

#Py 3
print "Python 3"

Note: Converting the block of code written in 2.7 is possible, but will take a very long time; Time that I do not have at the moment.

You could call your Python 2 snippet in a separate process from your Python 3 code (or vice versa) using the subprocess module . That would only work if you don't expect your Python context to be affected by the side effects of the Python 2 snippet, eg setting a variable from 2 that 3 will then use would not be possible.

If you wanted to use objects created by your Python 2 snippet in your Python 3 script, you could consider using pickle: serialize your objects to a local file in Python 2.7 and deserialize them from Python 3 - note that there are some changes between 2 and 3 that pickle will have to handle (see Unpickling a Python 2 object with Python 3 ).

To save you time: Automated Python 2 to 3 code translation

using 2to3 have worked wonders for me and is very simple to handle:

$ 2to3 example.py

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