0

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.

10
  • You might want to look at Six Commented Feb 15, 2018 at 15:51
  • 4
    There is no way to do this for two sections in the same file. You can put the second bit in another file and use subprocess.call Commented Feb 15, 2018 at 15:51
  • 1
    you cannot put print "Python 3" in a python 3 script, even somewhere where it's not executed. Commented Feb 15, 2018 at 15:52
  • You can use py2to3 Commented Feb 15, 2018 at 15:53
  • so, naughty boy, you don't put shebang on top of your scripts? -)) Commented Feb 15, 2018 at 15:53

2 Answers 2

2

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, e.g. 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).

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to use pickle to access the object from the subprocessed script? How about writing to a flat file, then reading it in later on in the script?
That would work and there are some options in pickle.load just for that purpose. I'll add that option to my response.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.