Most people knowns to detect python version by:
python -V
From the command line. But if you want to detect the python version from the code itself then you can use the sys.version:
Detect Python runtime with sys.version
import sys
print("Current Python version: ", sys.version)
result(this result is for portable WinPython on Windows):
Current Python version: 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)]
You can check more details with:
import sys
print("Python version: ", sys.version_info)
result:
Current Python version: sys.version_info(major=3, minor=5, micro=3, releaselevel='final', serial=0)
Detect Python runtime with platform
There is one more way by using platform:
import platform
print(platform.python_version())
result:
3.5.3
The other way by using platform is:
import platform
print(platform.sys.version)
result:
3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)]
Which way you are going to use depends on your needs - code compability and information required for the version.
Warning for older python versions
Warning in case of usage of Python 2 and older:
import sys
if sys.version_info[0] < 3:
raise Exception("Please upgrade to Python 3")
result:
Please upgrade to Python 3
Detect specific Python version and alert in case of other version:
import sys
if sys.version_info[0] != 3 or sys.version_info[0] != 7:
print("Please upgrade to the latest version 3.7.\n")
sys.exit(1)
print("Current Python version: ", sys.version)
result:
Please upgrade to the latest version 3.7.