在执行具有无效语法的脚本时检查 Python 解释器的版本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3760098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking Version of Python Interpreter Upon Execution of Script With Invalid Syntax
提问by Stunner
I have a Python script that uses Python version 2.6 syntax (Except erroras value:) which version 2.5 complains about. So in my script I have included some code to check for the Python interpreter version before proceeding so that the user doesn't get hit with a nasty error, however, no matter where I place that code, it doesn't work. Once it hits the strange syntax it throws the syntax error, disregarding any attempts of mine of version checking.
我有一个 Python 脚本,它使用 Python 2.6 版语法(除了错误作为值:) 2.5 版抱怨。所以在我的脚本中,我在继续之前包含了一些代码来检查 Python 解释器版本,这样用户就不会遇到令人讨厌的错误,但是,无论我把代码放在哪里,它都不起作用。一旦遇到奇怪的语法,它就会抛出语法错误,无视我的任何版本检查尝试。
I know I could simply place a try/except block over the area that the SyntaxError occurs and generate the message there but I am wondering if there is a more "elegant" way. As I am not very keen on placing try/except blocks all over my code to address the version issue. I looked into using an __ init__.py file, but the user won't be importing/using my code as a package, so I don't think that route will work, unless I am missing something...
我知道我可以简单地在 SyntaxError 发生的区域上放置一个 try/except 块并在那里生成消息,但我想知道是否有更“优雅”的方式。因为我不太热衷于在我的代码中放置 try/except 块来解决版本问题。我考虑使用 __ init__.py 文件,但用户不会将我的代码作为包导入/使用,所以我认为这条路线不会起作用,除非我遗漏了什么......
Here is my version checking code:
这是我的版本检查代码:
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()
采纳答案by bstpierre
Create a wrapper script that checks the version and calls your real script -- this gives you a chance to check the version before the interpreter tries to syntax-check the real script.
创建一个包装脚本来检查版本并调用您的真实脚本——这使您有机会在解释器尝试对真实脚本进行语法检查之前检查版本。
回答by eumiro
In sys.version_infoyou will find the version information stored in a tuple:
在sys.version_info你会发现存储在一个元组的版本信息:
sys.version_info
(2, 6, 6, 'final', 0)
Now you can compare:
现在你可以比较:
def isPythonVersion(version):
return version >= sys.version_info[0] + sys.version_info[1] / 10.
回答by Katriel
If speed is not a priority, you can avoid this problem entirely by using sys.exc_infoto grab the details of the last exception.
如果速度不是优先事项,您可以通过使用sys.exc_info获取最后一个异常的详细信息来完全避免此问题。
回答by Tony Veijalainen
Something like this in beginning of code?
在代码的开头是这样的吗?
import sys
if sys.version_info<(2,6):
raise SystemExit('Sorry, this code need Python 2.6 or higher')

