How to detect Python Version 2 or 3 in script?

2019-06-16 19:56发布

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()

2条回答
时光不老,我们不散
2楼-- · 2019-06-16 20:34

You can use the six library (https://pythonhosted.org/six/) too made more easy the writing of script working on both version. (And you have the macro six.PY2 and six.PY3 who indicate if you using python 2 ou 3)

And on python 2.6 and 2.7:

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

In the top of your file permit in a lot of case to made code à la Python 3 working on both 2 and 3.

查看更多
在下西门庆
3楼-- · 2019-06-16 20:39

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

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

For details see https://docs.python.org/2/library/sys.html .

查看更多
登录 后发表回答