Stu*_*ner 13 python interpreter
我有一个Python脚本使用Python版本2.6语法(错误为值 :),版本2.5抱怨.因此,在我的脚本中,我已经包含了一些代码来检查Python解释器版本,然后继续进行,以便用户不会遇到令人讨厌的错误,但是,无论我放置代码在哪里,它都不起作用.一旦它遇到奇怪的语法,就会抛出语法错误,忽略我的版本检查的任何尝试.
我知道我可以简单地在发生SyntaxError的区域放置一个try/except块并在那里生成消息,但我想知道是否有更"优雅"的方式.因为我不太热衷于在我的代码中放置try/except块来解决版本问题.我查看了使用__ init__.py文件,但是用户不会将我的代码作为包导入/使用,所以我不认为该路由会起作用,除非我遗漏了一些东西......
这是我的版本检查代码:
import sys
def isPythonVersion(version):
if float(sys.version[:3]) >= version:
return True
else:
return False
if not isPythonVersion(2.6):
print "You are running Python version", sys.version[:3], ", version 2.6 or 2.7 is required. Please update. Aborting..."
exit()
Run Code Online (Sandbox Code Playgroud)
Ton*_*nen 14
在代码开头这样的东西?
import sys
if sys.version_info<(2,6):
raise SystemExit('Sorry, this code need Python 2.6 or higher')
Run Code Online (Sandbox Code Playgroud)
bst*_*rre 13
创建一个包装器脚本来检查版本并调用您的真实脚本 - 这使您有机会在解释器尝试语法检查真实脚本之前检查版本.
在sys.version_info您将找到存储在元组中的版本信息:
sys.version_info
(2, 6, 6, 'final', 0)
Run Code Online (Sandbox Code Playgroud)
现在你可以比较:
def isPythonVersion(version):
return version >= sys.version_info[0] + sys.version_info[1] / 10.
Run Code Online (Sandbox Code Playgroud)