How can I check what version of the Python Interpreter is interpreting my script?
With six
module, you can do it by:
import six
if six.PY2:
# this is python2.x
else:
# six.PY3
# this is python3.x
To check from the command-line, in one single command, but include major, minor, micro version, releaselevel and serial, then invoke the same Python interpreter (i.e. same path) as you're using for your script:
> path/to/your/python -c "import sys; print('{}.{}.{}-{}-{}'.format(*sys.version_info))"
3.7.6-final-0
Note: .format()
instead of f-strings or '.'.join()
allows you to use arbitrary formatting and separator chars, e.g. to make this a greppable one-word string. I put this inside a bash utility script that reports all important versions: python, numpy, pandas, sklearn, MacOS, xcode, clang, brew, conda, anaconda, gcc/g++ etc. Useful for logging, replicability, troubleshootingm bug-reporting etc.
Put something like:
#!/usr/bin/env/python
import sys
if sys.version_info<(2,6,0):
sys.stderr.write("You need python 2.6 or later to run this script\n")
exit(1)
at the top of your script.
Note that depending on what else is in your script, older versions of python than the target may not be able to even load the script, so won't get far enough to report this error. As a workaround, you can run the above in a script that imports the script with the more modern code.
sys.version_info
doesn't seem to return a tuple
as of 3.7. Rather, it returns a special class, so all of the examples using tuples don't work, for me at least. Here's the output from a python console:
>>> import sys
>>> type(sys.version_info)
<class 'sys.version_info'>
I've found that using a combination of sys.version_info.major
and sys.version_info.minor
seems to suffice. For example,...
import sys
if sys.version_info.major > 3:
print('Upgrade to Python 3')
exit(1)
checks if you're running Python 3. You can even check for more specific versions with...
import sys
ver = sys.version_info
if ver.major > 2:
if ver.major == 3 and ver.minor <= 4:
print('Upgrade to Python 3.5')
exit(1)
can check to see if you're running at least Python 3.5.