简体   繁体   English

在同一脚本中使用两个单独的python版本

[英]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. 我有两个代码块,我想合并为一个python脚本。 One block of code is written in Python 2.7, the other in Python 3.6 其中一块代码是用Python 2.7编写的,另一块是用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? 我的问题是,有什么方法可以调用旧版本的python mid脚本来运行该特定代码块?

For instance, if I ran the following code, the script would error out because the second print statement is missing the parenthesis: 例如,如果我运行以下代码,该脚本将出错,因为第二个print语句缺少括号:

#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; 注意:可以转换用2.7编写的代码块,但这将花费很长时间。 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 . 您可以使用subprocess模块在与Python 3代码不同的过程中调用Python 2代码片段(反之亦然)。 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. 仅当您不希望Python上下文受Python 2代码段的副作用影响时,例如,将变量设置为2,然后3将无法使用,这才可行。

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 ). 如果要在Python 3脚本中使用由Python 2代码段创建的对象,则可以考虑使用pickle: 在Python 2.7中将对象序列化为本地文件然后从Python 3反序列化它们-请注意,在2和之间有一些更改3泡菜必须要处理(请参阅使用Python 3去除Python 2对象 )。

To save you time: Automated Python 2 to 3 code translation 为了节省时间: 自动化Python 2到3代码转换

using 2to3 have worked wonders for me and is very simple to handle: 使用2to3为我创造了奇迹,并且非常容易处理:

$ 2to3 example.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM