简体   繁体   English

获取 python 子进程的 output

[英]Getting the output of a python subprocess

I'm trying to capture the output here.我试图在这里捕获 output。 If, at the python prompt, I run如果在 python 提示符下,我运行

p = subprocess.Popen(["/path/to/search_by_hash.par", hash_str], 
                      stdout=subprocess.PIPE)

The return value (a list) prints to stdout, but isn't captured返回值(列表)打印到标准输出,但未被捕获

[4460475, 4406612, 4379510]

I've tried following it up with我试过跟进

value = p.communicate()[0]
value

..but value is an empty string, not the list of ints I was expecting, and which is being printed to stdout ..但是值是一个空字符串,而不是我期望的整数列表,并且正在打印到标准输出

I experimented with the solutions from Store output of subprocess.Popen call in a string but haven't been able to capture the output.我尝试了来自Store output 的解决方案。在字符串中调用 Popen,但无法捕获 output。

UPDATE:更新:

stderr doesn't seem to yield anything either...and the list I'm looking for is being printed out...just not having any luck in capturing it. stderr 似乎也没有产生任何东西......我正在寻找的列表正在打印出来......只是没有任何运气来捕捉它。 See below:见下文:

>>> p = subprocess.Popen(["/home/jfry/tools/search_by_hash.par", hash_str], 
                          stdout=subprocess.PIPE)
>>> 
[4460475, 4406612, 4379510]
    value, err  = p.communicate()
>>> value
''
>>> err

Thanks!谢谢!

Try checking stderr with p.communicate()[1] .尝试使用p.communicate()[1]检查stderr

Because the accepted answer does not solve the issue (at least for me):因为接受的答案并不能解决问题(至少对我而言):

To capture the stderr -output, the following should be done:要捕获stderr -输出,应执行以下操作:

import subprocess
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)        
output, err = p.communicate()

The crucial part is the parameter stderr=subprocess.PIPE , without this parameter the stderr -output will not be captured and err will be None .关键部分是参数stderr=subprocess.PIPE ,没有这个参数, stderr -output 将不会被捕获并且err将为None

If you are interested only in the stderr -output you actually may use:如果您只对stderr -输出感兴趣,您实际上可以使用:

p = subprocess.Popen(command, stderr=subprocess.PIPE)        
err = p.communicate()[1]

In this case p.communicate()[0] is None .在这种情况下p.communicate()[0]None

communicate is a method.沟通是一种方法。 So you should call it!所以你应该打电话!

out = p.communicate()

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

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