如何在使用新语言特性的程序中检查Python版本?

时间:2022-08-15 07:02:17

If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script?

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

How do I get control early enough to issue an error message and exit?

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

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.

例如,我有一个程序使用ternery操作符(2.5中新增)和“with”块(2.6中新增)。我编写了一个简单的解释性版本检查例程,这是脚本首先调用的。但它没有走那么远。相反,脚本在python编译期间失败,甚至在调用我的例程之前。因此,该脚本的用户看到了一些非常模糊的synax错误回溯——这几乎需要专家来推断,它只是运行错误版本的Python的情况。

I know how to check the version of Python. The issue is that some syntax is illegal in older versions of Python. Consider this program:

我知道如何检查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

When run under 2.4, I want this result

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

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

and not this result:

而不是这个结果:

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

(Channeling for a coworker.)

(引导同事。)

16 个解决方案

#1


102  

You can test using eval:

您可以使用eval进行测试:

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

Also, with is available in Python 2.5, just add from __future__ import with_statement.

另外,在Python 2.5中可以使用,只需从__future__导入with_statement添加。

EDIT: to get control early enough, you could split it into different .py files and check compatibility in the main file before importing (e.g. in __init__.py in a package):

编辑:为了尽早获得控制,您可以将其拆分为不同的.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 *

#2


102  

Have a wrapper around your program that does the following.

在您的程序周围有一个包装器,它执行以下操作。

import sys

req_version = (2,5)
cur_version = sys.version_info

if cur_version >= req_version:
   import myApp
   myApp.run()
else:
   print "Your Python interpreter is too old. Please consider upgrading."

You can also consider using sys.version(), if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.

您还可以考虑使用system .version(),如果您打算遇到使用2.0以前的Python解释器的人,但是您需要做一些正则表达式。

And there might be more elegant ways to do this.

也许有更优雅的方法。

#3


28  

Try

试一试

import platform
platform.python_version()

Should give you a string like "2.3.1". If this is not exactly waht you want there is a rich set of data available through the "platform" build-in. What you want should be in there somewhere.

应该给您一个类似“2.3.1”的字符串。如果这不是你想要的,你想要的是一个丰富的数据集通过“平台”内置。你想要的东西应该在那里。

#4


21  

Probably the best way to do do this version comparison is to use the sys.hexversion. This is important because comparing version tuples will not give you the desired result in all python versions.

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

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

#5


15  

import sys    
# prints whether python is version 3 or not
python_version = sys.version_info.major
if python_version == 3:
    print("is python 3")
else:
    print("not python 3")

#6


9  

Answer from Nykakin at AskUbuntu:

答:来自Nykakin at AskUbuntu:

You can also check Python version from code itself using platform module from standard library.

您还可以使用标准库中的平台模块从代码本身检查Python版本。

There are two functions:

有两个功能:

  • platform.python_version() (returns string).
  • platform.python_version()(返回字符串)。
  • platform.python_version_tuple() (returns tuple).
  • platform.python_version_tuple()(返回元组)。

The Python code

Create a file for example: version.py)

创建一个文件,例如:version.py)

Easy method to check version:

简单方法检查版本:

import platform

print(platform.python_version())
print(platform.python_version_tuple())

You can also use the eval method:

你也可以使用eval方法:

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

Run the Python file in a command line:

在命令行中运行Python文件:

$ python version.py 
2.7.11
('2', '7', '11')

The output of Python with CGI via a WAMP Server on Windows 10:

通过Windows 10上的WAMP服务器输出CGI的Python:

如何在使用新语言特性的程序中检查Python版本?


Helpful resources

#7


7  

Sets became part of the core language in Python 2.4, in order to stay backwards compatible. I did this back then, which will work for you as well:

set成为Python 2.4中的核心语言的一部分,以保持向后兼容。我当时做了这个,这对你们也有好处:

if sys.version_info < (2, 4):
    from sets import Set as set

#8


7  

Although the question is: How do I get control early enough to issue an error message and exit?

尽管问题是:如何及早获得控制,以便发出错误消息并退出?

The question that I answer is: How do I get control early enough to issue an error message before starting the app?

我要回答的问题是:在启动应用程序之前,如何尽早获得足够的控制来发布错误消息?

I can answer it a lot differently then the other posts. Seems answers so far are trying to solve your question from within Python.

和其他帖子相比,我可以有不同的回答。似乎到目前为止的答案都试图从Python中解决您的问题。

I say, do version checking before launching Python. I see your path is Linux or unix. However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn't be too hard.

我说,在启动Python之前进行版本检查。我看到你的路径是Linux或unix。但是我只能给你一个Windows脚本。我认为将它调整为linux脚本语法并不难。

Here is the DOS script with version 2.7:

以下是版本2.7的DOS脚本:

@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF

This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn't end your app to an exception due to different version syntax rules. That's three less possible security points of access.

这不会运行应用程序的任何部分,因此不会引发Python异常。它不创建任何临时文件或添加任何OS环境变量。它不会因为不同版本的语法规则而导致你的应用程序出现异常。这是三种不太可能的访问安全点。

The FOR /F line is the key.

对/F线是关键。

FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul

For multiple python version check check out url: http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17

对于多个python版本,请查看url: http://www.fpschultze.de/modules/smartfaq/faq.php?

And my hack version:

和我的破解版:

[MS script; Python version check prelaunch of Python module] http://pastebin.com/aAuJ91FQ

[女士脚本;Python版本检查Python模块的预启动]http://pastebin.com/aAuJ91FQ

#9


2  

As noted above, syntax errors occur at compile time, not at run time. While Python is an "interpreted language", Python code is not actually directly interpreted; it's compiled to byte code, which is then interpreted. There is a compile step that happens when a module is imported (if there is no already-compiled version available in the form of a .pyc or .pyd file) and that's when you're getting your error, not (quite exactly) when your code is running.

如上所述,语法错误发生在编译时,而不是运行时。虽然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:

你可以把编译步骤,使其在运行时发生的一行代码,如果你想要,通过使用eval,如上所述,但是我个人更喜欢避免这样做,因为它使Python运行时编译、执行可能不必要的一方面,另一方面,它创造了对我是什么感觉代码杂乱。(如果您愿意,可以生成生成代码的代码,生成代码,并在6个月内对其进行修改和调试。)所以我推荐的是这样的:

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

.. which I would do even if I only had one function that used newer syntax and it was very short. (In fact I would take every reasonable measure to minimize the number and size of such functions. I might even write a function like ifTrueAElseB(cond, a, b) with that single line of syntax in it.)

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

Another thing that might be worth pointing out (that I'm a little amazed no one has pointed out yet) is that while earlier versions of Python did not support code like

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

value = 'yes' if MyVarIsTrue else 'no'

..it did support code like

. .它确实支持代码

value = MyVarIsTrue and 'yes' or 'no'

That was the old way of writing ternary expressions. I don't have Python 3 installed yet, but as far as I know, that "old" way still works to this day, so you can decide for yourself whether or not it's worth it to conditionally use the new syntax, if you need to support the use of older versions of Python.

那是写三元表达式的老方法。我还没有安装Python 3,但据我所知,“旧”的方式在这方面的工作还需要这一天,所以你可以自己决定是否值得有条件地使用新的语法,如果您需要支持旧版本的Python的使用。

#10


2  

Put the following at the very top of your file:

在你的文件最上面写上以下内容:

import sys

if float(sys.version.split()[0][:3]) < 2.7:
    print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
    exit(1)

Then continue on with the normal Python code:

然后继续使用正常的Python代码:

import ...
import ...
other code...

#11


2  

import sys
sys.version

will be getting answer like this

会得到这样的答案吗

'2.7.6 (default, Oct 26 2016, 20:30:19) \n[GCC 4.8.4]'

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

here 2.7.6 is version

这是2.7.6版

#12


1  

I think the best way is to test for functionality rather than versions. In some cases, this is trivial, not so in others.

我认为最好的方法是测试功能而不是版本。在某些情况下,这是微不足道的,而在其他情况下则不然。

eg:

例如:

try :
    # Do stuff
except : # Features weren't found.
    # Do stuff for older versions.

As long as you're specific in enough in using the try/except blocks, you can cover most of your bases.

只要您在使用try/except块时足够明确,您就可以覆盖大部分基本块。

#13


1  

I just found this question after a quick search whilst trying to solve the problem myself and I've come up with a hybrid based on a few of the suggestions above.

我在尝试自己解决这个问题的时候,在快速搜索之后发现了这个问题,我基于上面的一些建议提出了一个混合型的问题。

I like DevPlayer's idea of using a wrapper script, but the downside is that you end up maintaining multiple wrappers for different OSes, so I decided to write the wrapper in python, but use the same basic "grab the version by running the exe" logic and came up with this.

我喜欢DevPlayer关于使用包装器脚本的想法,但是缺点是您最终为不同的操作系统维护了多个包装器,所以我决定用python编写包装器,但是使用相同的基本“通过运行exe获取版本”逻辑,并得出了这个结论。

I think it should work for 2.5 and onwards. I've tested it on 2.66, 2.7.0 and 3.1.2 on Linux and 2.6.1 on OS X so far.

我想应该是2。5岁以上。到目前为止,我已经在Linux上的2.66、2.7.0和3.1.2以及OS X上的2.6.1进行了测试。

import sys, subprocess
args = [sys.executable,"--version"]

output, error = subprocess.Popen(args ,stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()
print("The version is: '%s'"  %error.decode(sys.stdout.encoding).strip("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ,.+ \n") )

Yes, I know the final decode/strip line is horrible, but I just wanted to quickly grab the version number. I'm going to refine that.

是的,我知道最终的解码/条线很可怕,但我只是想快速抓取版本号。我将进一步完善它。

This works well enough for me for now, but if anyone can improve it (or tell me why it's a terrible idea) that'd be cool too.

这对我来说已经足够好了,但是如果有人能改进它(或者告诉我为什么这是个糟糕的主意),那也太酷了。

#14


0  

You can check with sys.hexversion or sys.version_info.

你可以和系统查询。hexversion或sys.version_info。

sys.hexversion isn't very human-friendly because it's a hexadecimal number. sys.version_info is a tuple, so it's more human-friendly.

sys。十六进制不是很人性化,因为它是十六进制数字。sys。version_info是一个tuple,因此它对人更友好。

Check for Python 3.6 or newer with sys.hexversion:

使用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()

Check for Python 3.6 or newer with sys.version_info:

使用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 is more human-friendly, but takes more characters. I would reccomend sys.hexversion, even though it is less human-friendly.

sys。version_info更人性化,但需要更多的字符。我将推荐系统。尽管它对人类不那么友好,但它是六向性的。

I hope this helped you!

我希望这对你有帮助!

#15


-2  

How about this:

这个怎么样:

import sys

def testPyVer(reqver):
  if float(sys.version[:3]) >= reqver:
    return 1
  else:
    return 0

#blah blah blah, more code

if testPyVer(3.0) == 1:
  #do stuff
else:
  #print python requirement, exit statement

#16


-3  

The problem is quite simple. You checked if the version was less than 2.4, not less than or equal to. So if the Python version is 2.4, it's not less than 2.4. What you should have had was:

问题很简单。检查版本是否小于2.4,是否小于或等于。如果Python版本是2.4,那么它不小于2.4。你应该拥有的是:

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

, not

,而不是

    if sys.version_info < (2, 4):

#1


102  

You can test using eval:

您可以使用eval进行测试:

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

Also, with is available in Python 2.5, just add from __future__ import with_statement.

另外,在Python 2.5中可以使用,只需从__future__导入with_statement添加。

EDIT: to get control early enough, you could split it into different .py files and check compatibility in the main file before importing (e.g. in __init__.py in a package):

编辑:为了尽早获得控制,您可以将其拆分为不同的.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 *

#2


102  

Have a wrapper around your program that does the following.

在您的程序周围有一个包装器,它执行以下操作。

import sys

req_version = (2,5)
cur_version = sys.version_info

if cur_version >= req_version:
   import myApp
   myApp.run()
else:
   print "Your Python interpreter is too old. Please consider upgrading."

You can also consider using sys.version(), if you plan to encounter people who are using pre-2.0 Python interpreters, but then you have some regular expressions to do.

您还可以考虑使用system .version(),如果您打算遇到使用2.0以前的Python解释器的人,但是您需要做一些正则表达式。

And there might be more elegant ways to do this.

也许有更优雅的方法。

#3


28  

Try

试一试

import platform
platform.python_version()

Should give you a string like "2.3.1". If this is not exactly waht you want there is a rich set of data available through the "platform" build-in. What you want should be in there somewhere.

应该给您一个类似“2.3.1”的字符串。如果这不是你想要的,你想要的是一个丰富的数据集通过“平台”内置。你想要的东西应该在那里。

#4


21  

Probably the best way to do do this version comparison is to use the sys.hexversion. This is important because comparing version tuples will not give you the desired result in all python versions.

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

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

#5


15  

import sys    
# prints whether python is version 3 or not
python_version = sys.version_info.major
if python_version == 3:
    print("is python 3")
else:
    print("not python 3")

#6


9  

Answer from Nykakin at AskUbuntu:

答:来自Nykakin at AskUbuntu:

You can also check Python version from code itself using platform module from standard library.

您还可以使用标准库中的平台模块从代码本身检查Python版本。

There are two functions:

有两个功能:

  • platform.python_version() (returns string).
  • platform.python_version()(返回字符串)。
  • platform.python_version_tuple() (returns tuple).
  • platform.python_version_tuple()(返回元组)。

The Python code

Create a file for example: version.py)

创建一个文件,例如:version.py)

Easy method to check version:

简单方法检查版本:

import platform

print(platform.python_version())
print(platform.python_version_tuple())

You can also use the eval method:

你也可以使用eval方法:

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

Run the Python file in a command line:

在命令行中运行Python文件:

$ python version.py 
2.7.11
('2', '7', '11')

The output of Python with CGI via a WAMP Server on Windows 10:

通过Windows 10上的WAMP服务器输出CGI的Python:

如何在使用新语言特性的程序中检查Python版本?


Helpful resources

#7


7  

Sets became part of the core language in Python 2.4, in order to stay backwards compatible. I did this back then, which will work for you as well:

set成为Python 2.4中的核心语言的一部分,以保持向后兼容。我当时做了这个,这对你们也有好处:

if sys.version_info < (2, 4):
    from sets import Set as set

#8


7  

Although the question is: How do I get control early enough to issue an error message and exit?

尽管问题是:如何及早获得控制,以便发出错误消息并退出?

The question that I answer is: How do I get control early enough to issue an error message before starting the app?

我要回答的问题是:在启动应用程序之前,如何尽早获得足够的控制来发布错误消息?

I can answer it a lot differently then the other posts. Seems answers so far are trying to solve your question from within Python.

和其他帖子相比,我可以有不同的回答。似乎到目前为止的答案都试图从Python中解决您的问题。

I say, do version checking before launching Python. I see your path is Linux or unix. However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn't be too hard.

我说,在启动Python之前进行版本检查。我看到你的路径是Linux或unix。但是我只能给你一个Windows脚本。我认为将它调整为linux脚本语法并不难。

Here is the DOS script with version 2.7:

以下是版本2.7的DOS脚本:

@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF

This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn't end your app to an exception due to different version syntax rules. That's three less possible security points of access.

这不会运行应用程序的任何部分,因此不会引发Python异常。它不创建任何临时文件或添加任何OS环境变量。它不会因为不同版本的语法规则而导致你的应用程序出现异常。这是三种不太可能的访问安全点。

The FOR /F line is the key.

对/F线是关键。

FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul

For multiple python version check check out url: http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17

对于多个python版本,请查看url: http://www.fpschultze.de/modules/smartfaq/faq.php?

And my hack version:

和我的破解版:

[MS script; Python version check prelaunch of Python module] http://pastebin.com/aAuJ91FQ

[女士脚本;Python版本检查Python模块的预启动]http://pastebin.com/aAuJ91FQ

#9


2  

As noted above, syntax errors occur at compile time, not at run time. While Python is an "interpreted language", Python code is not actually directly interpreted; it's compiled to byte code, which is then interpreted. There is a compile step that happens when a module is imported (if there is no already-compiled version available in the form of a .pyc or .pyd file) and that's when you're getting your error, not (quite exactly) when your code is running.

如上所述,语法错误发生在编译时,而不是运行时。虽然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:

你可以把编译步骤,使其在运行时发生的一行代码,如果你想要,通过使用eval,如上所述,但是我个人更喜欢避免这样做,因为它使Python运行时编译、执行可能不必要的一方面,另一方面,它创造了对我是什么感觉代码杂乱。(如果您愿意,可以生成生成代码的代码,生成代码,并在6个月内对其进行修改和调试。)所以我推荐的是这样的:

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

.. which I would do even if I only had one function that used newer syntax and it was very short. (In fact I would take every reasonable measure to minimize the number and size of such functions. I might even write a function like ifTrueAElseB(cond, a, b) with that single line of syntax in it.)

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

Another thing that might be worth pointing out (that I'm a little amazed no one has pointed out yet) is that while earlier versions of Python did not support code like

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

value = 'yes' if MyVarIsTrue else 'no'

..it did support code like

. .它确实支持代码

value = MyVarIsTrue and 'yes' or 'no'

That was the old way of writing ternary expressions. I don't have Python 3 installed yet, but as far as I know, that "old" way still works to this day, so you can decide for yourself whether or not it's worth it to conditionally use the new syntax, if you need to support the use of older versions of Python.

那是写三元表达式的老方法。我还没有安装Python 3,但据我所知,“旧”的方式在这方面的工作还需要这一天,所以你可以自己决定是否值得有条件地使用新的语法,如果您需要支持旧版本的Python的使用。

#10


2  

Put the following at the very top of your file:

在你的文件最上面写上以下内容:

import sys

if float(sys.version.split()[0][:3]) < 2.7:
    print "Python 2.7 or higher required to run this code, " + sys.version.split()[0] + " detected, exiting."
    exit(1)

Then continue on with the normal Python code:

然后继续使用正常的Python代码:

import ...
import ...
other code...

#11


2  

import sys
sys.version

will be getting answer like this

会得到这样的答案吗

'2.7.6 (default, Oct 26 2016, 20:30:19) \n[GCC 4.8.4]'

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

here 2.7.6 is version

这是2.7.6版

#12


1  

I think the best way is to test for functionality rather than versions. In some cases, this is trivial, not so in others.

我认为最好的方法是测试功能而不是版本。在某些情况下,这是微不足道的,而在其他情况下则不然。

eg:

例如:

try :
    # Do stuff
except : # Features weren't found.
    # Do stuff for older versions.

As long as you're specific in enough in using the try/except blocks, you can cover most of your bases.

只要您在使用try/except块时足够明确,您就可以覆盖大部分基本块。

#13


1  

I just found this question after a quick search whilst trying to solve the problem myself and I've come up with a hybrid based on a few of the suggestions above.

我在尝试自己解决这个问题的时候,在快速搜索之后发现了这个问题,我基于上面的一些建议提出了一个混合型的问题。

I like DevPlayer's idea of using a wrapper script, but the downside is that you end up maintaining multiple wrappers for different OSes, so I decided to write the wrapper in python, but use the same basic "grab the version by running the exe" logic and came up with this.

我喜欢DevPlayer关于使用包装器脚本的想法,但是缺点是您最终为不同的操作系统维护了多个包装器,所以我决定用python编写包装器,但是使用相同的基本“通过运行exe获取版本”逻辑,并得出了这个结论。

I think it should work for 2.5 and onwards. I've tested it on 2.66, 2.7.0 and 3.1.2 on Linux and 2.6.1 on OS X so far.

我想应该是2。5岁以上。到目前为止,我已经在Linux上的2.66、2.7.0和3.1.2以及OS X上的2.6.1进行了测试。

import sys, subprocess
args = [sys.executable,"--version"]

output, error = subprocess.Popen(args ,stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()
print("The version is: '%s'"  %error.decode(sys.stdout.encoding).strip("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ,.+ \n") )

Yes, I know the final decode/strip line is horrible, but I just wanted to quickly grab the version number. I'm going to refine that.

是的,我知道最终的解码/条线很可怕,但我只是想快速抓取版本号。我将进一步完善它。

This works well enough for me for now, but if anyone can improve it (or tell me why it's a terrible idea) that'd be cool too.

这对我来说已经足够好了,但是如果有人能改进它(或者告诉我为什么这是个糟糕的主意),那也太酷了。

#14


0  

You can check with sys.hexversion or sys.version_info.

你可以和系统查询。hexversion或sys.version_info。

sys.hexversion isn't very human-friendly because it's a hexadecimal number. sys.version_info is a tuple, so it's more human-friendly.

sys。十六进制不是很人性化,因为它是十六进制数字。sys。version_info是一个tuple,因此它对人更友好。

Check for Python 3.6 or newer with sys.hexversion:

使用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()

Check for Python 3.6 or newer with sys.version_info:

使用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 is more human-friendly, but takes more characters. I would reccomend sys.hexversion, even though it is less human-friendly.

sys。version_info更人性化,但需要更多的字符。我将推荐系统。尽管它对人类不那么友好,但它是六向性的。

I hope this helped you!

我希望这对你有帮助!

#15


-2  

How about this:

这个怎么样:

import sys

def testPyVer(reqver):
  if float(sys.version[:3]) >= reqver:
    return 1
  else:
    return 0

#blah blah blah, more code

if testPyVer(3.0) == 1:
  #do stuff
else:
  #print python requirement, exit statement

#16


-3  

The problem is quite simple. You checked if the version was less than 2.4, not less than or equal to. So if the Python version is 2.4, it's not less than 2.4. What you should have had was:

问题很简单。检查版本是否小于2.4,是否小于或等于。如果Python版本是2.4,那么它不小于2.4。你应该拥有的是:

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

, not

,而不是

    if sys.version_info < (2, 4):