Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect Python Version 2 or 3 in script?

I've written some scripts, which run either only with Version 2.x or some only with Version 3.x of Python.

How can I detect inside the script, if it's started with fitting Python Version?

Is there a command like:

major, minor = getPythonVersion()
like image 622
rundekugel Avatar asked Dec 09 '14 10:12

rundekugel


People also ask

How do I check the version of a Python script?

To check your Python version, run python ‐‐version in your command line (Windows), shell (Mac), or terminal (Linux/Ubuntu). To check your Python version in your script, run import sys to get the module and use sys. version to find detailed version information in your code.

How do I know if I have Python 2 installed?

Python is probably already installed on your system. To check if it's installed, go to Applications>Utilities and click on Terminal. (You can also press command-spacebar, type terminal, and then press Enter.) If you have Python 3.4 or later, it's fine to start out by using the installed version.

Is Python 2 the same as 3?

Python 3 is more in-demand and includes a typing system. Python 2 is outdated and uses an older syntax for the print function. While Python 2 is still in use for configuration management in DevOps, Python 3 is the current standard. Python (the code, not the snake) is a popular coding language to learn for beginners.


2 Answers

sys.version_info provides the version of the used Python interpreter.

Python 2

>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0)
>>> sys.version_info[0]
2

Python 3

>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=7, micro=10, releaselevel='final', serial=0)
>>> sys.version_info[0]
3

For details see the documentation.

like image 199
Klaus D. Avatar answered Sep 21 '22 18:09

Klaus D.


You can use the six library (https://pythonhosted.org/six/) to make it easier to write code that works on both versions. (It includes two booleans six.PY2 and six.PY3 which indicate whether the code is running in Python 2 or Python 3)

Also in Python 2.6 and 2.7, you can use

from __future__ import (print_function, unicode_literals, division)
__metaclass__ = type

to enable some of the Python 3 behaviour in a way that works on both 2 and 3.

like image 34
Cld Avatar answered Sep 24 '22 18:09

Cld