【问题标题】:How to run python 2.7 script in python 3.5 / Or what is the best option to run python scripts for 2.7 [duplicate]如何在python 3.5中运行python 2.7脚本/或者为2.7运行python脚本的最佳选择是什么[重复]
【发布时间】:2018-05-08 05:40:01
【问题描述】:

如果我已经安装了 Python 3,那么使用 Python 2.7 代码的最佳方式是什么?

我从未使用过 Python 2.7,因为我是 Python 新手,而且大多数视频教程和网络主题都说最好使用 Python 3。 但是当我尝试运行适用于 2.7 并且不存在于 Python 3 的代码时,有时它不起作用。 什么是更好的选择。在我的 PC 上同时使用 Python 2 和 3。或者尝试仅查找 Python 3 代码。或者以某种方式修改 Python 2.7 代码? 这些是错误:

IPython 6.1.0 -- An enhanced Interactive Python.

runfile('C:/Users/G/Desktop/image_recognition/new_test/GemData.py', wdir='C:/Users/G/Desktop/image_recognition/new_test')

Traceback (most recent call last):

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-1-02441e959cce>", line 1, in <module>
    runfile('C:/Users/G/Desktop/image_recognition/new_test/GemData.py', wdir='C:/Users/G/Desktop/image_recognition/new_test')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/G/Desktop/image_recognition/new_test/GemData.py", line 19
    print "error: image not read from file \n\n"        # print error message to std out
                                               ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(print "error: image not read from file \n\n"        # print error message to std out)?

【问题讨论】:

  • 你可以使用virtualenvs在同一台机器上运行不同的python版本

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


【解决方案1】:

您无法使用 Python 3 解释器运行当前代码,因此您有两种选择:将此代码转换为 Python 3 或使用 Python 2 运行。

将 2 移植到 3

有一些关于从python 2移植到3的资料:

Official docs

DigitalOcean tutorial

还有一个自动翻译工具:2to3。 我自己没用过,所以不能推荐,但是你可以看看,看看是否适合你的需求。

使用 python 2 运行

我认为这里最好的方法是使用 python 2 创建一个virtual environment。像这样

$ virtualenv -p python2 venv
$ source venv/bin/activate
$ python <your-script>.py

为了进一步阅读,有一种编写 python 2/3 兼容代码的技术。 See this.

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 2016-10-31
    • 1970-01-01
    • 2016-08-07
    • 2017-12-21
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多