从 Python 3 调用 Python 2 脚本 [英] Calling Python 2 script from Python 3
问题描述
我有两个脚本,主要是用 Python 3 编写的,第二个是用 Python 2 编写的(它也使用了 Python 2 库).
I have two scripts, the main is in Python 3, and the second one is written in Python 2 (it also uses a Python 2 library).
Python 2 脚本中有一个方法我想从 Python 3 脚本中调用,但是我不知道如何跨过这座桥.
There is one method in the Python 2 script I want to call from the Python 3 script, but I don't know how to cross this bridge.
推荐答案
使用 execnet.以下函数很有魅力:
Calling different python versions from each other can be done very elegantly using execnet. The following function does the charm:
import execnet
def call_python_version(Version, Module, Function, ArgumentList):
gw = execnet.makegateway("popen//python=python%s" % Version)
channel = gw.remote_exec("""
from %s import %s as the_function
channel.send(the_function(*channel.receive()))
""" % (Module, Function))
channel.send(ArgumentList)
return channel.receive()
示例:用 Python 2.7 编写的 my_module.py
:
Example: A my_module.py
written in Python 2.7:
def my_function(X, Y):
return "Hello %s %s!" % (X, Y)
然后调用下面的函数
result = call_python_version("2.7", "my_module", "my_function",
["Mr", "Bear"])
print(result)
result = call_python_version("2.7", "my_module", "my_function",
["Mrs", "Wolf"])
print(result)
结果
Hello Mr Bear!
Hello Mrs Wolf!
发生的事情是一个网关"被实例化等待对于带有 channel.receive()
的参数列表.一旦它进来,它就会被翻译并传递给my_function
.my_function
返回它生成的字符串,channel.send(...)
将字符串发回.在网关的另一端 channel.receive()
捕获该结果并将其返回给调用者.调用者最终打印由 my_function
在 python 3 模块中生成的字符串.
What happened is that a 'gateway' was instantiated waiting
for an argument list with channel.receive()
. Once it came in, it as been translated and passed to my_function
. my_function
returned the string it generated and channel.send(...)
sent the string back. On other side of the gateway channel.receive()
catches that result and returns it to the caller. The caller finally prints the string as produced by my_function
in the python 3 module.
这篇关于从 Python 3 调用 Python 2 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!