How do I check which version of Python is running my script?
This information is available in the sys.version
string in the sys
module:
>>> import sys
Human readable:
>>> print(sys.version) # parentheses necessary in python 3.
2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]
For further processing, use sys.version_info
or sys.hexversion
:
>>> sys.version_info
(2, 5, 2, 'final', 0)
# or
>>> sys.hexversion
34014192
To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:
assert sys.version_info >= (2, 5)
This compares major and minor version information. Add micro (=0
, 1
, etc) and even releaselevel (='alpha'
,'final'
, etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.
Which version of Python do I have installed?
python -V
http://docs.python.org/using/cmdline.html#generic-options
--version
may also work (introduced in version 2.5)
How do I detect the Python version at runtime?
Sure, take a look at sys.version
and sys.version_info
.
For example, to check that you are running Python 3.x, use
import sys
if sys.version_info[0] < 3:
raise Exception("Must be using Python 3")
Here, sys.version_info[0]
is the major version number. sys.version_info[1]
would give you the minor version number.
In Python 2.7 and later, the components of sys.version_info
can also be accessed by name, so the major version number is sys.version_info.major
.
See also How can I check for Python version in a program that uses new language features?
Checking actual version of Python running my code
There are several ways to detect the version of python your program is using.
From your question I get the feeling you're not understanding why $ python -V
and $ /usr/bin/python3 -V
are returning different versions. This is simply due to the python command being soft linked to a specific binary version (in your case, 2.7).
If you want to understand to which binary the python command on your shell is linked to:
$ readlink -f `which python`
/usr/bin/python2.7
Programmatically you can get your Python version with:
import sys
print(sys.version_info)
Which will result in the following output:
sys.version_info(major=3, minor=6, micro=8, releaselevel='final', serial=0)
You you're just wondering which version python is using when called via a shell, you can easily find out by:
$ python -V
Python 2.7.12
You can also inspect the header of your python file and check which interpreter is being used for that particular python script when you don't specify it when you're calling the script. (i.e: $ ./python_file.py
)
#!/usr/bin/python2.7
How to know which instance of Python my script is being ran on?
sys.version_info
and sys.version
contain the version of Python that is being run. sys.executable
contains the path to the specific interpreter running.
Python3:
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0)
>>> sys.version
'3.4.3 (default, Nov 17 2016, 01:08:31) \n[GCC 4.8.4]'
>>> sys.executable
'/usr/bin/python3'
Python2:
>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0)
>>> sys.version
'2.7.6 (default, Oct 26 2016, 20:30:19) \n[GCC 4.8.4]'
>>> sys.executable
'/usr/bin/python2'
The problem seems to be that your registry editor has set a different version set to run "on-click" for Python executables. You can fix that by running the Python installer for the version you want, and setting it to repair, or modifying "HKEY_CLASSES_ROOT\Python.File\Shell\open\command" to run the correct python executable (Should be "C:\Windows\py.exe"). See this image for where to find it.
If you are already using py.exe, adding a hashbang to the top of the file (#!Python<version>
, or to work with Unix executables, #!/usr/bin/env python<version>
) should help py.exe pick the correct executable to run.
To install using pip for a specific executable, run Path\To\Executable -m pip install <module>
.
To use modules from a different site-path, add the directory to the PYTHONPATH environment variable. Using import <file>
will check for modules in directories in the PYTHONPATH.
Check if python version is compatible with script before executing
sys.version_info[0]
is the major version only. So, it'll be 2
for all python 2.x versions. You're looking for sys.version_info[1]
, with the minor version:
# check for python 2
if sys.version_info[0] != 2:
raise Exception("Please use Python 2")
# check for 2.7+
if sys.version_info[1] < 7:
raise Exception("Please use Python 2.7+")
Alternatively, for more descriptive naming, you can use sys.version_info.major
instead of sys.version_info[0]
and sys.version_info.minor
instead of sys.version_info[1]
.
Also, make sure you add this near the top of your script so there are no incompatibilities before the line is hit and the exception is raised.
If your code uses incompatible syntax, then you should put the non-version checking code in a main function in a separate file, then import that after the check so that Python doesn't try to parse it.
How can I check for Python version in a program that uses new language features?
You can test using eval
:
try:
eval("1 if True else 2")
except SyntaxError:
# doesn't have ternary
Also, with
is available in Python 2.5, just add from __future__ import with_statement
.
EDIT: to get control early enough, you could split it into different .py
files and check compatibility in the main file before importing (e.g. in __init__.py
in a package):
# __init__.py
# Check compatibility
try:
eval("1 if True else 2")
except SyntaxError:
raise ImportError("requires ternary support")
# import from another module
from impl import *
How to make sure the script is executed by a specific version of python?
Just add this to the start of your script:
import sys
assert sys.version_info >= (3, 5, 2), "Python version too low."
Or if you prefer without assert
:
import sys
if not sys.version_info >= (3, 5, 2):
raise EnvironmentError("Python version too low.")
Or little bit more verbosely, but this will actually inform the user what version they need:
import sys
MIN = (3, 5, 2)
if not sys.version_info >= MIN:
raise EnvironmentError(
"Python version too low, required at least {}".format('.'.join(str(n) for n in MIN)))
Example output:
Traceback (most recent call last):
File "main.py", line 6, in <module>
"Python version too low, required at least {}".format('.'.join(str(n) for n in MIN)))
OSError: Python version too low, required at least 3.5.2
The specified minimum version tuple can be as precise as you want. These are all valid:
MIN = (3,)
MIN = (3, 5)
MIN = (3, 5, 2)
Detect python version in shell script
You could use something along the following lines:
$ python -c 'import sys; print(sys.version_info[:])'
(2, 6, 5, 'final', 0)
The tuple is documented here. You can expand the Python code above to format the version number in a manner that would suit your requirements, or indeed to perform checks on it.
You'll need to check $?
in your script to handle the case where python
is not found.
P.S. I am using the slightly odd syntax to ensure compatibility with both Python 2.x and 3.x.
Related Topics
What Is a Mixin and Why Is It Useful
How to Print a Number Using Commas as Thousands Separators
"Inconsistent Use of Tabs and Spaces in Indentation"
String Count With Overlapping Occurrences
Select Dataframe Rows Between Two Dates
What's the Difference Between Eval, Exec, and Compile
How to Capture Sigint in Python
How to Save/Restore a Model After Training
How to Split the Definition of a Long String Over Multiple Lines
Pass a List to a Function to Act as Multiple Arguments
Recursive Function Returning None in Python
Why Should Exec() and Eval() Be Avoided
Count the Number of Occurrences of a Character in a String
Which Python Memory Profiler Is Recommended
Remove All Occurrences of a Value from a List