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?
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.
How to detect Python Version 2 or 3 in script?
sys.version_info
provides the version of the used Python interpreter.
Python 2
>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0)
>>> sys.version_info[0]
2
Python 3
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=7, micro=10, releaselevel='final', serial=0)
>>> sys.version_info[0]
3
For details see the documentation.
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 *
Checking a Python module version at runtime
I'd stay away from hashing. The version of libxslt being used might contain some type of patch that doesn't effect your use of it.
As an alternative, I'd like to suggest that you don't check at run time (don't know if that's a hard requirement or not). For the python stuff I write that has external dependencies (3rd party libraries), I write a script that users can run to check their python install to see if the appropriate versions of modules are installed.
For the modules that don't have a defined 'version' attribute, you can inspect the interfaces it contains (classes and methods) and see if they match the interface they expect. Then in the actual code that you're working on, assume that the 3rd party modules have the interface you expect.
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.
Runtime.getRuntime().exec does not find the default python version
If you run exec("python test.py")
in Java, will try to resolve python
to an executable file in the same way as any other application does.
Assuming that you are using UNIX, Linux or Mac OSX, the sequence is roughly as follows:
The JVM performs a
fork
syscall to create a child process. The child process inherits the environment variables of the parent (JVM) process.The child process performs an exec syscall, passing it the command name, arguments and environment variables.
If the command name is a simple name, the syscall attempts to resolving the name to a pathname by searching the directories on the command search path for an executable file; i.e. one with the appropriate execute permission set.
If an executable is found, it is either loaded into the child process or interpreted as a script, depending on its signature.
In your case, it is step 3 that is not working. Specifically, it finds the wrong version of python
on the search path. The search path is determined by the PATH
environment variable ... as inherited from the parent JVM.
So, if you get different results in an interactive shell and from Java, that most likely means that they have different PATH
variables. That is the first thing to check. For example, in your Java application, see what this outputs:
System.out.println(System.environ().get("PATH"));
and check that the first python
command it would find is the version that you want.
Possible solutions:
- Set
PATH
appropriately before starting the JVM - Use
ProcessBuilder
to execute the external command with a modified environment - Use an absolute pathname for the
python
command. - If this is Python 2 vs 3, give the command name as
python2
orpython3
. (A typical Linux package etc will link frompython2
andpython3
to the correct executables.)
How do I check the versions of Python modules?
Use pip
instead of easy_install
.
With pip, list all installed packages and their versions via:
pip freeze
On most Linux systems, you can pipe this to grep
(or findstr
on Windows) to find the row for the particular package you're interested in.
Linux:
pip freeze | grep lxml
lxml==2.3
Windows:
pip freeze | findstr lxml
lxml==2.3
For an individual module, you can try the __version__
attribute. However, there are modules without it:
python -c "import requests; print(requests.__version__)"
2.14.2
python -c "import lxml; print(lxml.__version__)"
Traceback (most recent call last):
File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute 'version'
Lastly, as the commands in your question are prefixed with sudo
, it appears you're installing to the global python environment. I strongly advise to take look into Python virtual environment managers, for example virtualenvwrapper.
How to have the python program version only in setup.cfg for runtime and packaging?
Two options I can think of – I'd go with the first.
1. Use setup.cfg
's attr:
support to read the version from the source
setup.cfg
[metadata]
version = attr:my_app.__version__
my_app/init.py
# ...
__version__ = '0.1.3'
2. Use importlib.metadata
to read the version from the installation metadata
(New in Python 3.8, has backports for older Pythons)
from importlib.metadata import version
my_version = version('my_app')
How do I tell a Python script to use a particular version
You can add a shebang line the to the top of the script:
#!/usr/bin/env python2.7
But that will only work when executing as ./my_program.py
.
If you execute as python my_program.py
, then the whatever Python version that which python
returns will be used.
In re: to virtualenv use: virtualenv -p /usr/bin/python3.2
or whatever to set it up to use that Python executable.
Related Topics
What Determines Which Strings Are Interned and When
When Are Objects Garbage Collected in Python
Tkinter Vanishing Photoimage Issue
Differencebetween .Quit and .Quit in Pygame
How to Count the Nan Values in a Column in Pandas Dataframe
A Tool to Convert Matlab Code to Python
Progress Indicator During Pandas Operations
Ssl Insecureplatform Error When Using Requests Package
Adding a Legend to Pyplot in Matplotlib in the Simplest Manner Possible
Super() Raises "Typeerror: Must Be Type, Not Classobj" for New-Style Class
How to Add a Custom Ca Root Certificate to the Ca Store Used by Pip in Windows
Best Way to Format Integer as String with Leading Zeros
Processing Single File from Multiple Processes
Does Python Support Multiprocessor/Multicore Programming
How Does Multiplication Differ for Numpy Matrix VS Array Classes
Why Does Python Pep-8 Strongly Recommend Spaces Over Tabs for Indentation