Python 打印版本号的方法有两个,对 python 2.x、3.x 都有效

 

Python版本号通过代码获取的两种方法

# print python version
def print_version():
    ## 方式1: python 2.x, 3.x (2.7.13, 3.6.1, 3.7.2)
    import platform
    print("\npython version: %s" % (platform.python_version()))
    
    ## 方式2: 
    import sys
    print("\npython version: %s" % (sys.version))
    print("\npython version_info: %s" % (json.dumps(sys.version_info)))
    print("\npython version_info.major: %s" % (sys.version_info.major))

运行结果:

python version: 3.7.2

python version: 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43) 
[Clang 6.0 (clang-600.0.57)]

python version_info: [3, 7, 2, "final", 0]

python version_info.major: 3

 

 

Python版本号通过命令行获取的两种方法

Python 2.7.6

# /usr/local/bin/python
Python 2.7.6 (default, Dec 18 2018, 13:43:48) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.python_version()
'2.7.6'
>>> print(platform.python_version())
2.7.6
>>> 
>>> import sys
>>> sys.version
'2.7.6 (default, Dec 18 2018, 13:43:48) \n[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]'
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0)
>>> sys.version_info.major
2

 

Python 2.7.5

# python
Python 2.7.5 (default, Oct 30 2018, 23:45:53) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.python_version()
'2.7.5'
>>> print(platform.python_version())
2.7.5

 

Python 3.6.1

$ python3
Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.python_version()
'3.6.1'
>>> 
>>> print(platform.python_version())
3.6.1

 

Python 3.7.2

$ python3.7
Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform
>>> platform.python_version()
'3.7.2'
>>> print(platform.python_version())
3.7.2
>>> 
>>> import sys
>>> sys.version
'3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43) \n[Clang 6.0 (clang-600.0.57)]'
>>> print(sys.version)
3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43) 
[Clang 6.0 (clang-600.0.57)]
>>> sys.version_info
sys.version_info(major=3, minor=7, micro=2, releaselevel='final', serial=0)
>>> sys.version_info.major
3

 

 

参考推荐

Python urllib2.URLError: urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

MacOSX:Do you want the application “Python.app” to accept incoming network connections?

Mac 高效程序猿开发必备软件