pythonpython-3.xversionpython-2.xsix

How to detect Python Version 2 or 3 in script?


I've written some scripts, which run either only with Version 2.x or some only with Version 3.x of Python.

How can I detect inside the script, if it's started with fitting Python Version?

Is there a command like:

major, minor = getPythonVersion()

Solution

  • sys.version_info provides the version of the used Python interpreter.

    Python 2

    >>> import sys
    >>> sys.version_info
    sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0)
    >>> sys.version_info[0]
    2
    

    Python 3

    >>> import sys
    >>> sys.version_info
    sys.version_info(major=3, minor=7, micro=10, releaselevel='final', serial=0)
    >>> sys.version_info[0]
    3
    

    For details see the documentation.