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

6 投票
3 回答
17127 浏览
提问于 2025-04-17 09:27

我正在尝试保存我用 subprocess.call 得到的输出,但我总是遇到以下错误:

AttributeError: 'int' object has no attribute 'communicate'

我的代码如下:

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

3 个回答

1

你应该使用子进程

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

这是因为 subprocess.call 返回的是一个整数:

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.

看起来你想要使用 subprocess.Popen()

下面是我通常用来实现这个功能的一段代码:

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
5

你应该使用 subprocess.Popen() 而不是 call()

你还需要把它改成 p2.communicate()[0]

撰写回答