In Python, it’s often necessary to check which version of the interpreter is running your script. This can be useful for a variety of reasons, such as ensuring compatibility with specific features or libraries. In this tutorial, we’ll explore several ways to determine the Python version.
Using the sys
Module
The sys
module provides several ways to access information about the Python interpreter, including its version. You can use the sys.version
string to get a human-readable representation of the version:
import sys
print(sys.version)
This will output a string like (2, 5, 2, 'final', 0)
or 3.9.2 (default, Oct 8 2021, 12:12:24)
. The exact format may vary depending on the version of Python you’re using.
If you need to access the version information in a more structured way, you can use the sys.version_info
tuple:
import sys
print(sys.version_info)
This will output a tuple like (2, 5, 2, 'final', 0)
or (3, 9, 2, 'final', 0)
. You can access individual elements of the tuple using indexing.
Another way to get the version information is by using the sys.hexversion
integer:
import sys
print(sys.hexversion)
This will output an integer like 34014192
or 33883376
.
Using the platform
Module
Alternatively, you can use the platform
module’s python_version()
function to get the version of Python as a string:
from platform import python_version
print(python_version())
This will output a string like 3.9.2
.
Checking Version Requirements
If your script requires a specific version of Python, you can use an assertion to check the version:
import sys
assert sys.version_info >= (3, 6)
This will raise an AssertionError
if the version of Python is less than 3.6.
Command-Line Option
Finally, you can also check the Python version from the command line using the -V
option:
python -V
This will output a string like Python 3.9.2
.
In summary, there are several ways to check the Python version, including using the sys
module, the platform
module, and the command-line option. By choosing the method that best fits your needs, you can ensure that your scripts are compatible with specific versions of Python.