import sys
# global variable
pyVersion = 2 # set default python version to 2.x
# init global variable(s)
def init():
global pyVersion
pyVersion = sys.version_info[0] # get major version of python
def test():
print(pyVersion)
if __name__ == '__main__':
init()
test()
运行情况:
D:\profile\Desktop>checkVersion.py
2
检查出了python的主版本号后,我们就可以利用pyVersion这个变量作为判断条件,写出不同的语句,以适应在不同python版本下的程序。
因为python2与3的差别还是挺大的,所以这种用法可以写出在不同版本上通用的程序,比较方便!