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

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

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

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

    With six module, you can do it by:

    import six
    
    if six.PY2:
      # this is python2.x
    else:
      # six.PY3
      # this is python3.x
    
    0 讨论(0)
  • 2020-11-22 04:52

    To check from the command-line, in one single command, but include major, minor, micro version, releaselevel and serial, then invoke the same Python interpreter (i.e. same path) as you're using for your script:

    > path/to/your/python -c "import sys; print('{}.{}.{}-{}-{}'.format(*sys.version_info))"
    
    3.7.6-final-0
    

    Note: .format() instead of f-strings or '.'.join() allows you to use arbitrary formatting and separator chars, e.g. to make this a greppable one-word string. I put this inside a bash utility script that reports all important versions: python, numpy, pandas, sklearn, MacOS, xcode, clang, brew, conda, anaconda, gcc/g++ etc. Useful for logging, replicability, troubleshootingm bug-reporting etc.

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

    Put something like:

    #!/usr/bin/env/python
    import sys
    if sys.version_info<(2,6,0):
      sys.stderr.write("You need python 2.6 or later to run this script\n")
      exit(1)
    

    at the top of your script.

    Note that depending on what else is in your script, older versions of python than the target may not be able to even load the script, so won't get far enough to report this error. As a workaround, you can run the above in a script that imports the script with the more modern code.

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

    sys.version_info doesn't seem to return a tuple as of 3.7. Rather, it returns a special class, so all of the examples using tuples don't work, for me at least. Here's the output from a python console:

    >>> import sys
    >>> type(sys.version_info)
    <class 'sys.version_info'>
    

    I've found that using a combination of sys.version_info.major and sys.version_info.minor seems to suffice. For example,...

    import sys
    if sys.version_info.major > 3:
        print('Upgrade to Python 3')
        exit(1)
    

    checks if you're running Python 3. You can even check for more specific versions with...

    import sys
    ver = sys.version_info
    if ver.major > 2:
        if ver.major == 3 and ver.minor <= 4:
            print('Upgrade to Python 3.5')
            exit(1)
    

    can check to see if you're running at least Python 3.5.

    0 讨论(0)
提交回复
热议问题