如果我有一个Python脚本,至少需要一个特定的 在Python版本中,优雅地失败的正确方式是什么 当使用早期版本的Python启动脚本时?

如何尽早获得控制权以发出错误消息 并退出吗?

For example, I have a program that uses the ternery operator (new in 2.5) and "with" blocks (new in 2.6). I wrote a simple little interpreter-version checker routine which is the first thing the script would call ... except it doesn't get that far. Instead, the script fails during python compilation, before my routines are even called. Thus the user of the script sees some very obscure synax error tracebacks - which pretty much require an expert to deduce that it is simply the case of running the wrong version of Python.

我知道如何检查Python的版本。问题是一些语法在旧版本的Python中是非法的。考虑这个程序:

import sys
if sys.version_info < (2, 4):
    raise "must use python 2.5 or greater"
else:
    # syntax error in 2.4, ok in 2.5
    x = 1 if True else 2
    print x

当在2.4下运行时,我想要这个结果

$ ~/bin/python2.4 tern.py 
must use python 2.5 or greater

而不是这个结果:

$ ~/bin/python2.4 tern.py 
  File "tern.py", line 5
    x = 1 if True else 2
           ^
SyntaxError: invalid syntax

(为同事通灵。)


当前回答

问题很简单。您检查了版本是否小于2.4,而不是小于或等于。因此,如果Python版本是2.4,则不小于2.4。 你应该拥有的是:

    if sys.version_info **<=** (2, 4):

,而不是

    if sys.version_info < (2, 4):

其他回答

你可以和系统确认。Hexversion或sys.version_info。

sys。十六进制对人类不是很友好,因为它是十六进制数。sys。Version_info是一个元组,因此更人性化。

使用sys.hexversion检查Python 3.6或更新版本:

import sys, time
if sys.hexversion < 0x30600F0:
    print("You need Python 3.6 or greater.")
    for _ in range(1, 5): time.sleep(1)
    exit()

使用sys.version_info检查Python 3.6或更新版本:

import sys, time
if sys.version_info[0] < 3 and sys.version_info[1] < 6:
    print("You need Python 3.6 or greater.")
    for _ in range(1, 5): time.sleep(1)
    exit()

sys。Version_info更加人性化,但需要更多字符。我推荐sys。Hexversion,尽管它不太适合人类。

我希望这对你有所帮助!

你可以使用eval进行测试:

try:
  eval("1 if True else 2")
except SyntaxError:
  # doesn't have ternary

此外,with在Python 2.5中可用,只需从__future__ import with_statement中添加。

编辑:为了尽早获得控制权,你可以将它分割成不同的.py文件,并在导入前检查主文件的兼容性(例如在包中的__init__.py中):

# __init__.py

# Check compatibility
try:
  eval("1 if True else 2")
except SyntaxError:
  raise ImportError("requires ternary support")

# import from another module
from impl import *

如上所述,语法错误发生在编译时,而不是在运行时。虽然Python是一种“解释型语言”,但Python代码实际上并不是直接解释的;它被编译成字节码,然后进行解释。当导入模块时(如果没有.pyc或.pyd文件形式的已编译版本可用)会发生编译步骤,这时您会得到错误,而不是(确切地说)当代码正在运行时。

You can put off the compile step and make it happen at run time for a single line of code, if you want to, by using eval, as noted above, but I personally prefer to avoid doing that, because it causes Python to perform potentially unnecessary run-time compilation, for one thing, and for another, it creates what to me feels like code clutter. (If you want, you can generate code that generates code that generates code - and have an absolutely fabulous time modifying and debugging that in 6 months from now.) So what I would recommend instead is something more like this:

import sys
if sys.hexversion < 0x02060000:
    from my_module_2_5 import thisFunc, thatFunc, theOtherFunc
else:
    from my_module import thisFunc, thatFunc, theOtherFunc

. .即使我只有一个使用新语法的函数,而且它非常短,我也会这样做。(事实上,我会采取一切合理的措施来减少这类函数的数量和大小。我甚至可以写一个像ifTrueAElseB(cond, a, b)这样的函数,其中只有一行语法。)

另一件可能值得指出的事情(我有点惊讶还没有人指出这一点)是,虽然早期版本的Python不支持类似于

value = 'yes' if MyVarIsTrue else 'no'

..它支持类似

value = MyVarIsTrue and 'yes' or 'no'

这是写三元表达式的老方法。我还没有安装Python 3,但据我所知,这种“旧”方式至今仍然有效,所以如果你需要支持使用旧版本的Python,你可以自己决定是否有条件地使用新语法。

import sys
sys.version

会得到这样的答案吗

'2.7.6(默认,2016年10月26日,20:30:19)\n[GCC 4.8.4]'

这里是2.7.6版本

进行版本比较的最好方法可能是使用sys.hexversion。这一点很重要,因为比较版本元组不会在所有python版本中都得到想要的结果。

import sys
if sys.hexversion < 0x02060000:
    print "yep!"
else:
    print "oops!"