How do I check what version of Python is running m

2018-12-31 12:20发布

How can I check what version of the Python Interpreter is interpreting my script?

18条回答
怪性笑人.
2楼-- · 2018-12-31 12:54

To see a MSDOS script to check the version before running the Python interpreter (to avoid Python version syntax exceptions) See solution:

How can I check for Python version in a program that uses new language features?

and

MS script; Python version check prelaunch of Python module http://pastebin.com/aAuJ91FQ (script likely easy to convert to other OS scripts.)

查看更多
几人难应
3楼-- · 2018-12-31 12:55

Here's a short commandline version which exits straight away (handy for scripts and automated execution):

python -c "print(__import__('sys').version)"

Or just the major, minor and micro:

python -c "print(__import__('sys').version_info[:1])" # (2,)
python -c "print(__import__('sys').version_info[:2])" # (2, 7)
python -c "print(__import__('sys').version_info[:3])" # (2, 7, 6)
查看更多
刘海飞了
4楼-- · 2018-12-31 12:56

Like Seth said, the main script could check sys.version_info (but note that that didn't appear until 2.0, so if you want to support older versions you would need to check another version property of the sys module).

But you still need to take care of not using any Python language features in the file that are not available in older Python versions. For example, this is allowed in Python 2.5 and later:

try:
    pass
except:
    pass
finally:
    pass

but won't work in older Python versions, because you could only have except OR finally match the try. So for compatibility with older Python versions you need to write:

try:
    try:
        pass
    except:
        pass
finally:
    pass
查看更多
忆尘夕之涩
5楼-- · 2018-12-31 12:58

With six module, you can do it by:

import six

if six.PY2:
  # this is python2.x
else:
  # six.PY3
  # this is python3.x
查看更多
何处买醉
6楼-- · 2018-12-31 12:59

The simplest way

Just type python in your terminal and you can see the version as like following

desktop:~$ python
Python 2.7.6 (default, Jun 22 2015, 18:00:18) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
查看更多
唯独是你
7楼-- · 2018-12-31 13:02
import sys
sys.version.split(' ')[0]

sys.version gives you what you want, just pick the first number :)

查看更多
登录 后发表回答