ImportError:无法导入名称getoutput

时间:2018-08-10 14:30:55

标签: python-3.x python-2.7 subprocess python-2to3

我正在使用future将代码从Python 2移植到Python 3。

getoutput设为未来时,导入将从

更改

from commands import getoutputfrom subprocess import getoutput

我的代码使用getoutput测试需求文件。

但是,当我运行测试时,出现以下错误:

from subprocess import getoutput
ImportError: cannot import name getoutput

如何避免这种情况?还是有其他替代方法可以将getoutput从Python2扩展到Python3

2 个答案:

答案 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

它有效。