简体   繁体   English

如何将子进程 stderr 保存到变量?

[英]How do I save subprocess stderr to variable?

I am using the following code to run a subprocess.我正在使用以下代码来运行子进程。 The command 'cmd' might at times fail and I wish to save the stderr output to a variable for further examination.命令“cmd”有时可能会失败,我希望将 stderr output 保存到变量中以供进一步检查。

def exec_subprocess(cmd)
    with open('f.txt', 'w') as f:
        p = Popen(cmd, stderr=f)
        p.wait()

Right now as you can see I am saving stderr to file.现在你可以看到我正在将 stderr 保存到文件中。 I then later save the file content to a list using readlines() which seems inefficient.然后,我稍后使用 readlines() 将文件内容保存到列表中,这似乎效率低下。 What I would like instead is something like:我想要的是:

def exec_subprocess(cmd)
    err = []
    p = Popen(cmd, stderr=err)
    p.wait()
    return err

How do I efficiently save stderr to list?如何有效地将 stderr 保存到列表中?

You should use:你应该使用:

p=Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
outs, errs = p.communicate()

if you want to assign the output of stderr to a variable.如果要将 stderr 的 output 分配给变量。

Popen.communicate Popen.communicate

using the subprocess module 使用子流程模块

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

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