How to check version of Python (both command-line and programmatically)

Sometimes you might want to confirm if your program will run / is running under Python 2.x or 3.x. We have a very simple way to do the stuff.

Command Line Method

It is really easy to confirm a Python version using the option --version of the interpreter.

ares$ python --version Python 2.7.10

ares$ python3 --version Python 3.5.1

You can also start the interpreter, and see the version information in the welcome message.

ares$ python Python 2.7.10 (default, Sep 23 2015, 04:34:21)? [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>

Programmatically Check

You can also check the version on-the-fly when your program runs. Just a short piece of code:

import sys # if it is Python2.x is_py2=(sys.version_info[0] == 2) # if it is Python3.x is_py3=(sys.version_info[0] == 3)

By integrating the two values, you can check the current running environment and implement compatibility stuffs, such as __unicode__() and __str__() for Python 2.

Let's take a close look at what sys.version_info returns:

>>> import sys >>> sys.version_info sys.version_info(major=2, minor=7, micro=10, releaselevel='final', serial=0) >>>
Total Views: 9238