我习惯future
将代码从Python 2移植到Python 3。
未来时getoutput
,导入从
from commands import getoutput
至 from subprocess import getoutput
我的代码用于getoutput
测试需求文件。
但是,当我运行测试时,出现以下错误:
from subprocess import getoutput
ImportError: cannot import name getoutput
如何避免这种情况?还是有其他替代方法可用于getoutput
从Python2到Python3的未来发展
您可以使用sys.version_info
具有major
属性的对象获取Python安装的主版本。然后,您可以检查此值以查看您是在Python 2还是Python 3+上运行。
import sys
if sys.version_info.major == 2:
from commands import getoutput
else:
from subprocess import getoutput
如果几乎没有条件导入和其他简单语句,这将起作用。否则,您可以看一下兼容性包,如six
,该包用于为您提供特定的层,从而使您可以在2和3中运行代码。六个包含一个模块six.moves
,其中包含six.moves.getoutput
一个将getoutput
正确解决的问题。(相当于commands.getoutput
2.7和subprocess.getoutput
3+)。
另一种选择是在导入周围使用try-except块,并让其自行解决。
try:
from subprocess import getoutput
except ImportError:
from commands import getoutput
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句