Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect the Python version at runtime? [duplicate]

Tags:

python

I have a Python file which might have to support Python versions < 3.x and >= 3.x. Is there a way to introspect the Python runtime to know the version which it is running (for example, 2.6 or 3.2.x)?

like image 509
priya Avatar asked Jan 31 '12 11:01

priya


People also ask

What version of Python do I have runtime?

You can check the version of Python that is running a program, at runtime. Then check the content of the sys. version_info property. This property returns the Python version as a tuple.

How can I tell how many Python versions I have?

Open Command line: Start menu -> Run and type cmd. Type: C:\Python34\python.exe.


2 Answers

Sure, take a look at sys.version and sys.version_info.

For example, to check that you are running Python 3.x, use

import sys if sys.version_info[0] < 3:     raise Exception("Must be using Python 3") 

Here, sys.version_info[0] is the major version number. sys.version_info[1] would give you the minor version number.

In Python 2.7 and later, the components of sys.version_info can also be accessed by name, so the major version number is sys.version_info.major.

See also How can I check for Python version in a program that uses new language features?

like image 197
Chris Avatar answered Sep 25 '22 10:09

Chris


Try this code, this should work:

import platform print(platform.python_version()) 
like image 32
Avinash Avatar answered Sep 25 '22 10:09

Avinash