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!
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With