python子进程隐藏标准输出并等待它完成

python子进程隐藏标准输出并等待它完成

本文介绍了python子进程隐藏标准输出并等待它完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

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

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

正如你们所见,method_a 有一个调用 somtoolbox 程序的子进程.但是这个程序有一个很长的标准输出,我想隐藏它.我试过了:

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)

但它返回了这句话:

cat: record error: Broked Pipe

(这是葡萄牙语句子的翻译:cat: erro de gravação: Pipe quebrado")(我来自巴西)

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

此外,我还有其他方法(例如method_b),在method_a之后调用,并且在子进程完成过程之前运行tis方法.

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:somtoolbox 是一个 Java 程序,它将长输出提供给终端.尝试过:

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!

推荐答案

最好的方法是将输出重定向到/dev/null.你可以这样做:

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)

然后等到它完成,你可以在 Popen 对象上使用 .wait() ,让你:

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 将包含进程的返回码.

retcode will then contain the return code of the process.

附加:如评论中所述,这不会隐藏 stderr.要隐藏标准错误,您可以这样做:

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()

这篇关于python子进程隐藏标准输出并等待它完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 21:31