How can I print the version number of the current Python installation from my script?
7 Answers
Try
import sys
print(sys.version)
This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.
import platform
print(platform.python_version())
This prints something like
3.7.2
Try
python --version
or
python -V
This will return a current python version in terminal.
-
4Nice and simple! I would recommend the latter method because older version of Python do not support the "--version" flag. Plus, the less typing for me, the better. Nov 14, 2014 at 14:33
-
41No it should not be the answer, because Thomas specifically asked "...in the output?". He wasn't asking how to discover which version he had installed, he was asking how to include that information into a 'print' statement. Dec 5, 2017 at 14:33
import sys
expanded version
sys.version_info
sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0)
specific
maj_ver = sys.version_info.major
repr(maj_ver)
'3'
or
print(sys.version_info.major)
'3'
or
version = ".".join(map(str, sys.version_info[:3]))
print(version)
'3.2.2'
If you are using jupyter notebook Try:
!python --version
If you are using terminal Try:
python --version
If you would like to have tuple type of the version, you can use the following:
import platform
print(platform.python_version_tuple())
print(type(platform.python_version_tuple()))
# <class 'tuple'>
If you specifically want to output the python version from the program itself, you can also do this. Uses the simple python version printing method we know and love from the terminal but does it from the program itself:
import os
if __name__ == "__main__":
os.system('python -V') # can also use python --version