我正在使用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
答案 0 :(得分:2)
您可以使用具有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
。 (相当于2.7中的commands.getoutput
和3+中的subprocess.getoutput
)。
另一种选择是在导入过程中使用try-except块,并让其自行解决。
try:
from subprocess import getoutput
except ImportError:
from commands import getoutput
答案 1 :(得分:1)
我看到我缺少安装别名语句:
from future import standard_library
standard_library.install_aliases()
from subprocess import getoutput
但是,这出现了PEP-8
错误:Module level import not at top of file
所以我用future.moves
代替:
from future.moves.subprocess import getoutput
它有效。