在同一程序中使用Python 2和3库的正确方法(如果有的话)是什么?

时间:2015-03-21 04:55:43

标签: python python-2.7 python-3.x

我希望编写一个python脚本,需要执行任务'A'和任务'B'。幸运的是,这两个任务都有现有的Python模块,但不幸的是,可以执行任务'A'的库只是Python 2,而可以执行任务'B'的库只是Python 3。

在我的情况下,这些库很小并且很容易获得许可,因此我可以毫不费力地将它们都转换为Python 3。但是我想知道在这种情况下做什么是“正确”的事情 - 例如,是否有一些特殊的方法可以将用Python 2编写的模块直接导入到Python 3程序中?

2 个答案:

答案 0 :(得分:4)

"对"方法是将Py2-only模块转换为Py3并使用pull请求(或非git上游repos的等效方法)向上游提供转换。认真。让py2和py3包一起工作的可怕黑客值得努力。

答案 1 :(得分:1)

我认为你知道像2to3这样的工具,它们的目的是让代码更容易移植到py3k,只需在这里为其他人重复一遍即可。参考

在我必须使用python3和python2库的情况下,我已经能够使用subprocess模块解决它。或者,我已经解决了这个问题,shell脚本将python2脚本的输出管道传递给python3脚本,反之亦然。这当然只涵盖了一小部分用例,但是如果您在2& 2之间传输文本(或者甚至是可选对象)。 3,它(或更经过深思熟虑的变体)应该有用。

据我所知,在混合版本的python时,没有最佳实践

我向你展示了一个丑陋的黑客

考虑以下简单的玩具示例,涉及三个文件:

# py2.py
# file uses python2, here illustrated by the print statement
def hello_world():
    print 'hello world'

if __name__ == '__main__':
    hello_world()

# py3.py
# there's nothing py3 about this, but lets assume that there is, 
# and that this is a library that will work only on python3 
def count_words(phrase):
     return len(phrase.split())

# controller.py
# main script that coordinates the work, written in python3
# calls the python2 library through subprocess module
# the limitation here is that every function needed has to have a script 
# associated with it that accepts command line arguments.
import subprocess
import py3

if __name__ == '__main__':
    phrase = subprocess.check_output('python py2.py', shell=True)
    num_words = py3.count_words(phrase)
    print(num_words)

# If I run the following in bash, it outputs `2`
hals-halbook: toy hal$ python3 controller.py 
2
相关问题