How can I print the version number of the current Python installation from my script?
10 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.
1 Comment
import platform
print(platform.python_version())
This prints something like
3.7.2
2 Comments
python -c "print(__import__('platform').python_version())"You can retrieve the Python version using various methods, depending on your specific needs and context. Here are some different ways to print the Python version:
- Using the sys module:
import sys print("Python version") print(sys.version) print("Version info.") print(sys.version_info) - Using the platform module:
import platform print(platform.python_version()) - From the command line (Terminal or Command Prompt):
python --version - Using the sysconfig module (for more detailed information):
import sysconfig print(sysconfig.get_python_version()) - Using the platform module (detailed version information):
import platform print(platform.python_build()) - In an interactive Python shell:
>>> import sys >>> sys.version
These methods will provide you with different levels of detail about the Python version currently installed on your system.
3 Comments
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'
Comments
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
2 Comments
python executable, so this would fail.