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

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

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

22条回答
  •  青春惊慌失措
    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)
    
    

    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.

提交回复
热议问题