我正在寻找一种方法来测试用Python 3.6开发的代码是否将与Python 2.7兼容。理想情况下-如果不是,我希望以某种方式指出无效的语法。谢谢
答案 0 :(得分:-2)
是的。使用python2.7 yourScript.py
执行代码。如果某些模块需要python3。*,则可以仅为python2.7编写第二个脚本? hacky,但这是快速而懒惰的解决方案。
您绝对应该在启动时检查版本。此代码段会使用正确的版本自动重新启动脚本:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pythonVersionCheck.py
import sys
import os
# Color codes for output
CRED = '\033[91m'
CGREEN = '\033[92m'
CEND = '\033[0m'
# Desired python version number
scriptVersion = "3.6"
# Check if script is executed with root. Get rid of this block if you don't need it
if os.geteuid() != 0:
print(CRED + "\nRestart the script with root privileges: 'sudo python"
+ scriptVersion + " " + sys.argv[0] + "'\n" + CEND)
sys.exit(0)
# Check if the script is running with the desired python version
if sys.version[:3] == scriptVersion:
print(CGREEN + "Script running with Python " + scriptVersion + CEND)
else:
print(CRED + "Script not running with Python " + scriptVersion + ". Restarting." + CEND)
try:
os.execv(sys.executable, ['python' + scriptVersion] + sys.argv)
except OSError as error:
print(CRED + "An error occured: " + str(error) + CEND)
# YOUR CODE HERE
阅读Python2。*和Python3。* here之间的可移植性。
编辑:根据@MisterMiyagi的建议,此处有一些更改。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pythonVersionCheck.py
import sys
import subprocess
import platform
# Desired python version number
scriptVersion = "2.7"
usedVersion = "{0}.{1}".format(sys.version_info.major,sys.version_info.minor)
opSys = platform.system()
# Check if the script is running with the desired python version
if usedVersion == scriptVersion:
print("Script running with Python " + scriptVersion)
else:
print("Script not running with Python " + scriptVersion + ". Restarting.")
if opSys == 'Linux' or opSys == 'Darwin':
subprocess.call('python' + scriptVersion + ' ' + sys.path[0] + '/' +
sys.argv[0], shell=True)
elif opSys is 'Windows':
print("py -" + scriptVersion + ' ' + sys.argv[0])
subprocess.call("py -" + scriptVersion + ' ' + sys.argv[0], shell=True)
else:
print("Can't detect os.")
# YOUR CODE HERE
它现在使用subprocess
而不是os.execv
。
现在,它使用sys.version_info
而不是sys.version
。
现在,它可以检查用户运行的平台,因此可以移植到Linux,Windows和Appletoshwin。