Reputation:
How can I print the version number of the current Python installation from my script?
Upvotes: 643
Views: 540774
Reputation: 4827
In Jupyter Notebooks it can easily be done using 'cell magic':
%%bash
python --version
or
%%bash
python -V
Upvotes: 0
Reputation: 16733
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:
import sys
print("Python version")
print(sys.version)
print("Version info.")
print(sys.version_info)
import platform
print(platform.python_version())
python --version
import sysconfig
print(sysconfig.get_python_version())
import platform
print(platform.python_build())
>>> import sys
>>> sys.version
These methods will provide you with different levels of detail about the Python version currently installed on your system.
Upvotes: 86
Reputation: 119
For the sake of having a one-liner :
print(__import__('sys').version)
Upvotes: 5
Reputation: 157
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
Upvotes: -3
Reputation: 463
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'>
Upvotes: 0
Reputation: 860
If you are using jupyter notebook Try:
!python --version
If you are using terminal Try:
python --version
Upvotes: 9
Reputation: 116161
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.
Upvotes: 818
Reputation: 61683
import platform
print(platform.python_version())
This prints something like
3.7.2
Upvotes: 279
Reputation: 539
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'
Upvotes: 43