简体   繁体   English

Python:使用stdout从subprocess.call捕获输出

[英]Python: Catching the output from subprocess.call with stdout

So im trying to save the output from my subprocess.call but I keep getting the following error: AttributeError: 'int' object has no attribute 'communicate' 所以我试图保存我的subprocess.call的输出,但我不断收到以下错误: AttributeError: 'int' object has no attribute 'communicate'

Code is as follows: 代码如下:

p2 = subprocess.call(['./test.out', 'new_file.mfj', 'delete1.out'], stdout = PIPE)
output = p2.communicate[0]

You're looking for subprocess.Popen() instead of call() . 您正在寻找subprocess.Popen()而不是call()

You also need to change it to p2.communicate()[0] . 您还需要将其更改为p2.communicate()[0]

That's because subprocess.call returns an int: 那是因为subprocess.call返回一个int:

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

    Run the command described by args. Wait for command to complete, then return the returncode attribute.

It looks like you want subprocess.Popen(). 看起来你想要subprocess.Popen()。

Here's a typical piece of code I have to do this: 这是我必须执行的典型代码:

p = Popen(cmd, stdout=PIPE, stderr=PIPE, bufsize=256*1024*1024)
output, errors = p.communicate()
if p.returncode:
    raise Exception(errors)
else:
    # Print stdout from cmd call
    print output

You should use subprocess 你应该使用子进程

    try:            
        subprocess.check_output(['./test.out', 'new_file.mfj', 'delete1.out'], shell=True, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as exception:
        print exception.output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM