python subprocess hide stdout and wait it to complete

旧时模样 提交于 2019-12-06 03:39:59

问题


I have this code:

def method_a(self):
    command_line = 'somtoolbox GrowingSOM ' + som_prop_path
    subprocess.Popen(shlex.split(command_line))
    ......

def method_b(self): .....
....

and like you all see, method_a has a subprocess that is calling the somtoolbox program. But this program have a long stdout, and I want to hide it. I tried:

subprocess.Popen(shlex.split(command_line), stdout=subprocess.PIPE)

But it returned this sentence:

cat: record error: Broked Pipe   

(this is a translation of the portuguese sentence: "cat: erro de gravação: Pipe quebrado") (I'm from brazil)

Also, I have other methods (like method_b there), that are called after the method_a, and tis methods are running before the subprocess complete the process.

How I can hide the stdout at all (and don't want it anywhere), and make the other code wait for the subprocess to finish the execution ?

Obs: The somtoolbox is a java program, that gives the long output to the terminal. Tried:

outputTuple = subprocess.Popen(shlex.split(command_line), stdout = subprocess.PIPE).communicate()

but continuous returning output to the shell. Help!


回答1:


The best way to do that is to redirect the output into /dev/null. You can do that like this:

devnull = open('/dev/null', 'w')
subprocess.Popen(shlex.split(command_line), stdout=devnull)

Then to wait until it's done, you can use .wait() on the Popen object, getting you to this:

devnull = open('/dev/null', 'w')
process = subprocess.Popen(shlex.split(command_line), stdout=devnull)
retcode = process.wait()

retcode will then contain the return code of the process.

ADDITIONAL: As mentioned in comments, this won't hide stderr. To hide stderr as well you'd do it like so:

devnull = open('/dev/null', 'w')
process = subprocess.Popen(shlex.split(command_line), stdout=devnull, stderr=devnull)
retcode = process.wait()



回答2:


Popen.communicate is used to wait for the process to terminate. For example:

from subprocess import PIPE, Popen
outputTuple = Popen(["gcc", "--version"], stdout = PIPE).communicate()

will return a tuple of strings, one for stdout and another one for stderr output.



来源:https://stackoverflow.com/questions/3125525/python-subprocess-hide-stdout-and-wait-it-to-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!