有没有办法阻止Python 3脚本在Python 2中被调用?

问题描述 投票:0回答:4

我要交作业,我非常担心,由于单个TA有很多项目要运行,所以会使用

python
来调用,这会调用python 2.7,当程序为
python3.2编写时
应该这样称呼。这会导致语法错误,并且我会失去分数。我知道在做业余项目时,这种情况经常发生,如果助教遇到这种情况,我认为他不会跟进。

我要提交一个

readme
,但我想知道是否有一种方法可以在我的代码中捕获这个而不需要太多麻烦,并打印一条声明,表示将项目重新运行为
python3.2 project.py
。我可以
try: print "Rerun project…" except:pass
,但是有更好的方法吗?

python python-3.x
4个回答
10
投票

你可以这样做:

import sys
print(sys.version_info)

从 Python 2.7 开始,您还可以使用:

print(sys.version_info.major, sys.version_info.minor, sys.version_info.micro)

当当前运行的 Python 版本不符合预期时,您可以使用

sys.version_info
的值打印警告。

您还可以使用:

import platform
print(platform.python_version())

7
投票

像这样启动程序怎么样:

#!/usr/bin/env python
# -*- coding: utf8 -*-

import sys

if sys.version_info < (3,0,0):
    print(__file__ + ' requires Python 3, while Python ' + str(sys.version[0] + ' was detected. Terminating. '))
    sys.exit(1)

5
投票

这实际上是一个比你一开始认为的更难实现的问题。

假设您有以下代码:

import platform
import sys

if platform.python_version().startswith('2'):
    # This NEVER will be executed no matter the version of Python
    # because of the two syntax errors below...
    sys.stdout.write("You're using python 2.x! Python 3.2+ required!!!")
    sys.exit()     
else:
    # big program or def main(): and calling main() .. whatever
    # later in that file/module:
    x, *y=(1,2,3)      # syntax error on Python 2...
    # or
    print 'test'       # syntax error on Python 3...

else
子句下的两个语法错误之一是在实际执行
if
之前生成的,无论用于运行它的Python版本如何。因此,程序不会像你想象的那样优雅退出;无论如何,它都会因语法错误而失败。

解决方法是将您的实际程序放入外部文件/模块中,并以这种方式包装在

try/except
中:

try:
    import Py3program    # make sure it has syntax guaranteed to fail on 
                         # Python 2 like    x, *y=1,2,3
except SyntaxError:
    sys.stdout.write(error message)
    sys.exit()

# rest of the Python 3 program...

如果您的助教将使用 shebang 执行该文件,那将是一个更好的方法。也许问问助教他将如何运行你的脚本?


0
投票

十年过去了,这老栗子依然咬人。就我而言,由于第 434 行出现

python2
SyntaxError
解释器本身停止了脚本的运行。唉,错误信息并不丰富,而且因为脚本根本没有运行过,所以
platform.python_version()
也没有运行过。因此
platform
测试没有帮助

因为我不想让文件在

python2
中运行,所以我只是在相关行中添加了注释,所以
SyntaxError
看起来像:

y$ python2 alarm_clock.py
  File "alarm_clock.py", line 434
    txt=f"The time is %M minutes past %{AUDIO_H} o'clock" # <- YOU NEED PYTHON3 IF YOU ARE SEEING THIS IN AN ERROR.
                                                        ^
SyntaxError: invalid syntax
© www.soinside.com 2019 - 2024. All rights reserved.