How do I check which version of Python is running my script?
Quickly identify your script’s Python version using the following script:
This prints the major and minor Python version numbers you're running, and you're good to go.
Asserting a Minimum Python Version
To make sure your script is running on the minimum required Python version, use assertion:
This stops your script from being executed on incompatible Python versions and causing a total bummer.
Checking Specific Version Features
Sometimes you want to use features that only exist in later Python versions. In those cases, it's usually safer to do a 'peekaboo' and check for the feature first, but you can also check the version.
Way less chances to trip over this check, and hey, self-explanatory too.
Digging into Version Details
For a closer look into your Python
version, use sys.version
to get a verbose, human-friendly version output. Like a version string with all the bells and whistles.
This gives you all three numbers, major, minor and micro, along with additional info. Kind of like Python's full name, if it had one.
Advanced Version Comparisons
Maybe you're an advanced Pythonista who needs to do some fancy stuff with hexadecimal version data:
The sys.hexversion
check allows you to do these comparisons in a single integer. It's Python's version of a secret handshake.
Checking Python Version in the Terminal
Or suppose you want to check the Python version before entering 'Buzz Lightyear mode' and running your script. You can do this straight from the command-line:
Or if you're IPython or Jupyter notebooks fan:
Extra Tools for Version Info
If you want more tools in your belt, you can also get Python version using the platform
module:
Another pretty way to print your Python version, no muss, no fuss.
Dealing with Version-Specific Imports
Imagine Python modules as the cast of Friends. Some versions know Rachel, others know Monica (just a joke, folks!).
With this way, no matter the version, you have a fallback. And you keep your code friendly and sociable across all Python versions.
Communicating Version Requirements
Just like a good front door sign, let your users know if their Python version lacks the wow factor :
Using sys.version_info like a Pro
Remember sys.version_info
from before? It's a tuple so you can use it for complex comparisons:
Showing Python Docs Some Love
While you're at it, don't forget to check out the detailed docs for things like sys.hexversion
. You'll be surprised how much more there is to Python versioning!
Was this article helpful?