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

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

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

22条回答
  •  隐瞒了意图╮
    2020-11-22 04:51

    Just for fun, the following is a way of doing it on CPython 1.0-3.7b2, Pypy, Jython and Micropython. This is more of a curiosity than a way of doing it in modern code. I wrote it as part of http://stromberg.dnsalias.org/~strombrg/pythons/ , which is a script for testing a snippet of code on many versions of python at once, so you can easily get a feel for what python features are compatible with what versions of python:

    via_platform = 0
    check_sys = 0
    via_sys_version_info = 0
    via_sys_version = 0
    test_sys = 0
    try:
        import platform
    except (ImportError, NameError):
        # We have no platform module - try to get the info via the sys module
        check_sys = 1
    
    if not check_sys:
        if hasattr(platform, "python_version"):
            via_platform = 1
        else:
            check_sys = 1
    
    if check_sys:
        try:
            import sys
            test_sys = 1
        except (ImportError, NameError):
            # just let via_sys_version_info and via_sys_version remain False - we have no sys module
            pass
    
    if test_sys:
        if hasattr(sys, "version_info"):
            via_sys_version_info = 1
        elif hasattr(sys, "version"):
            via_sys_version = 1
        else:
            # just let via_sys remain False
            pass
    
    if via_platform:
        # This gives pretty good info, but is not available in older interpreters.  Also, micropython has a
        # platform module that does not really contain anything.
        print(platform.python_version())
    elif via_sys_version_info:
        # This is compatible with some older interpreters, but does not give quite as much info.
        print("%s.%s.%s" % sys.version_info[:3])
    elif via_sys_version:
        import string
        # This is compatible with some older interpreters, but does not give quite as much info.
        verbose_version = sys.version
        version_list = string.split(verbose_version)
        print(version_list[0])
    else:
        print("unknown")
    

提交回复
热议问题