DEV Community

loading...

detecting Python version in a script

Tony Colston
wanna be gamedev ... all around nerd and dev
・1 min read

Recently I needed to know if a program I was running was using Python2 or Python3.

There are a couple of ways to do this inside the Python interpreter.

The most obscure way (IMO) is probably the most reliable

import sys
major_version = sys.version_info[0]
print(major_version)

This method is reliable but how did I know to look at position 0 in sys.version_info? That looks odd and feels like magic.

In Python 2.6 sys.version_info was a tuple. It was not a class so sys.version_info[0] is the major number (aka 2). In Python 2.7 and up the sys.version_info became effectively a class and this type of code became valid

print(sys.version_info.major)

That code above will fail in an older Python so the safe way to check your version is the ugly way :(

Discussion (0)