[英]subprocess checkoutput error
I am trying to check the usage of check_output using he below script and running into compilation error,where am I going wrong? 我正在尝试使用下面的脚本检查check_output的使用情况并运行编译错误,我哪里错了?
import os
import subprocess
from subprocess import check_output
#result = subprocess.check_output(['your_program.exe', 'arg1', 'arg2'])
SCRIPT_ROOT=subprocess.check_output(["pwd","shell=True"])
print SCRIPT_ROOT
def main ():
pass
if __name__ == '__main__':
main()
Traceback (most recent call last):
File "test.py", line 3, in <module>
from subprocess import check_output
ImportError: cannot import name check_output
check_output
has been introduced in Python 2.7. check_output
已在Python 2.7中引入。 If you're using an earlier version of python, it's just not there. 如果您使用的是早期版本的python,那就不存在了。
Alternative is to use Popen
. 另一种方法是使用
Popen
。
output = subprocess.Popen(['pwd'], stdout=subprocess.PIPE).communicate()[0]
Proof of this can be found here . 这方面的证据可以在这里找到。
New function: the subprocess module's check_output() runs a command with a specified set of arguments and returns the command's output as a string when the command runs without error, or raises a CalledProcessError exception otherwise.
新函数:子进程模块的check_output()运行带有指定参数集的命令,并在命令运行时无错误地返回命令的输出作为字符串,否则引发CalledProcessError异常。
Demo of the substitute. 替补的演示。
import subprocess
cmd = subprocess.Popen(['pwd'], stdout=subprocess.PIPE)
output = cmd.communicate()[0]
print cmd.returncode
print output
Output 产量
> python p.py
/Users/vlazarenko/tests
The only real difference is that Popen
won't throw an exception when command returns a non-zero code. 唯一真正的区别是,当命令返回非零代码时,
Popen
不会抛出异常。
There is no check_output
in 2.6. 2.6中没有
check_output
。 But if you look at the 2.7 source , it's trivial. 但是如果你看看2.7源代码 ,那就太微不足道了。
In fact, a common way to deal with this is: 事实上,解决这个问题的常用方法是:
import subprocess
try:
check_output = subprocess.check_output
except AttributeError:
def check_output(*popenargs, **kwargs):
# lines 537-545 copied and pasted from 2.7 source
This does of course require that your code be PSFL-compatible (which it almost certainly is, but if it matters, I wouldn't take legal advice from a random guy on SO). 这当然要求你的代码与PSFL兼容(几乎可以肯定,但是如果重要的话,我不会从SO上的随机人那里获得法律建议)。
Another option is to use subprocess32
, a backport of the 3.2.3 subprocess
module to Python 2.4+, which gives you not only the new 2.7 features and fixes, but a bunch of newer ones. 另一个选择是使用
subprocess32
subprocess
模块的后端到Python 2.4+,它不仅为您提供新的2.7功能和修复,而且还提供了一些较新的功能和修复。 (Personally, whenever I'm writing 2/3 code, I end up writing with subprocess.Popen…
and have to either change it to with contextlib.closing(subprocess.Popen…
or with subprocess32.Popen
…) (就个人而言,每当我编写2/3代码时,我最终都会
with subprocess.Popen…
编写with subprocess.Popen…
并且必须将其更改为with contextlib.closing(subprocess.Popen…
或者with subprocess32.Popen
...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.