【问题标题】:Is it possible to run parts of a code in python 2.x while the rest is written in python 3.x?是否可以在 python 2.x 中运行部分代码,而其余部分是用 python 3.x 编写的?
【发布时间】:2017-06-08 02:55:58
【问题描述】:

是否有可能有 python 3.x 代码并在其中执行 2.x 代码(例如函数调用)?

#Code written in python 3.x
.
.
.
.
.
.


#This is the python 2.x part with Function2x() written in python 2.x
Function2x()
#End of python 2.x part


#Code written in python 3.x
.
.
.
.
.
.

这会被认为是不好的做法吗?如果是这样,如果将代码从 3.x 移植到 2.x 不是一种选择,如何规避这个问题?

【问题讨论】:

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


【解决方案1】:

一般来说这可能是不可能的。至少没有简单的方法。

但是根据您要解决的问题,有一些解决方法。例如如果你有与 python2 解释器不兼容的 python3 代码并且你必须在 python2 中运行它,你可以尝试使用future 模块。

如果你有 python2 代码可以转换为 python3,那么你可以使用@smart-manoj 提到的2to3 实用程序。

此外,如果您只有一些简单的 python3 方法可以运行并返回单个结果,您可以考虑使用 subprocess.call 方法从 python2 调用外部 python3 进程。这当然也可以反过来使用,即从 python3 调用 python2 解释器。但是您很快就会遇到该解决方案的一些问题,因此我不建议您这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 2020-11-03
    • 2020-10-22
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多