How do I check what version of Python is running my script?

前端 未结 22 2073
醉话见心
醉话见心 2020-11-22 04:11

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

相关标签:
22条回答
  • 2020-11-22 04:30

    Several answers already suggest how to query the current python version. To check programmatically the version requirements, I'd make use of one of the following two methods:

    # Method 1: (see krawyoti's answer)
    import sys
    assert(sys.version_info >= (2,6))
    
    # Method 2: 
    import platform
    from distutils.version import StrictVersion 
    assert(StrictVersion(platform.python_version()) >= "2.6")
    
    0 讨论(0)
  • 2020-11-22 04:30

    The even simpler simplest way:

    In Spyder, start a new "IPython Console", then run any of your existing scripts.

    Now the version can be seen in the first output printed in the console window:

    "Python 3.7.3 (default, Apr 24 2019, 15:29:51)..."

    0 讨论(0)
  • 2020-11-22 04:32

    This information is available in the sys.version string in the sys module:

    >>> import sys
    

    Human readable:

    >>> print(sys.version)  # parentheses necessary in python 3.       
    2.5.2 (r252:60911, Jul 31 2008, 17:28:52) 
    [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]
    

    For further processing:

    >>> sys.version_info
    (2, 5, 2, 'final', 0)
    # or
    >>> sys.hexversion
    34014192
    

    To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:

    assert sys.version_info >= (2, 5)
    

    This compares major and minor version information. Add micro (=0, 1, etc) and even releaselevel (='alpha','final', etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.

    0 讨论(0)
  • 2020-11-22 04:34

    From the command line (note the capital 'V'):

    python -V
    

    This is documented in 'man python'.

    From IPython console

    !python -V
    
    0 讨论(0)
  • 2020-11-22 04:34

    I like sys.hexversion for stuff like this.

    http://docs.python.org/library/sys.html#sys.hexversion

    >>> import sys
    >>> sys.hexversion
    33883376
    >>> '%x' % sys.hexversion
    '20504f0'
    >>> sys.hexversion < 0x02060000
    True
    
    0 讨论(0)
  • 2020-11-22 04:38

    Use platform's python_version from the stdlib:

    >>> from platform import python_version
    >>> print(python_version())
    2.7.8
    
    0 讨论(0)
提交回复
热议问题