python - 从 Python 3 调用 Python 2 脚本

标签 python

我有两个脚本,主要是用 Python 3 编写的,第二个是用 Python 2 编写的(它也使用 Python 2 库)。

我想从 Python 3 脚本调用 Python 2 脚本中的一种方法,但我不知道如何跨过这座桥。

最佳答案

使用execnet 可以非常优雅地相互调用不同的python 版本。 .以下函数具有魅力:

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:

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_functionmy_function 返回它生成的字符串,channel.send(...) 将字符串发回。在网关的另一端,channel.receive() 捕获该结果并将其返回给调用者。调用者最终打印出由 my_function 在 python 3 模块中生成的字符串。

关于python - 从 Python 3 调用 Python 2 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27863832/

相关文章:

python - 使用从数据库恢复的 cookie 时看到重复的 cookie

python - 实现这种二维数值积分的计算速度更快的方法是什么?

python - Pytesseract TesseractNotFoundError [Python 3]

python - 如何使用 youtube-dl 只下载缩略图?

Python用星号替换字符串的某些部分

c++ - OpenCV/C++ 程序比它的 numpy 对应程序慢,我该怎么办?

Python gdal投影信息

python - 如何获得我们拍摄外星人的时间?

python - 编程新手,这段 Python 代码的计算时间似乎很长

python - 如何在 Windows 中执行 Python 脚本?