To ascertain which version of Python is executing a given script, there are several methods available. The most straightforward approach is to utilize the sys.version string provided by the sys module. This string offers both human-readable information and values suitable for further processing.
import sys print(sys.version) # parentheses necessary in Python 3
For detailed analysis, you can leverage sys.version_info or sys.hexversion:
sys.version_info sys.hexversion
To guarantee that a script runs only with a specified minimum Python version, include the following assertion in your code:
assert sys.version_info >= (2, 5)
This assertion verifies major and minor version compatibility. You can add more detailed checks for micro and release level comparisons as needed.
The above is the detailed content of How Can I Identify the Python Version Running My Script?. For more information, please follow other related articles on the PHP Chinese website!