views:

2125

answers:

5

I have a binary named A that generates output when called. If I call it from a Bash shell, most of the output is suppressed by A > /dev/null. All of the output is suppressed by A &> /dev/null

I have a python script named B that needs to call A. I want to be able to generate output from B, while suppressing all the output from A.

From within B, I've tried os.system('A'), os.system('A > /dev/null'), and os.system('A &> /dev/null'), os.execvp('...'), etc. but none of those suppress all the output from A.

I could run B &> /dev/null, but that suppresses all of B's output too and I don't want that.

Anyone have suggestions?

+2  A: 

As the os.system() docs mention, use the subprocess module, and, if you like, set stdout=open(os.devnull, 'w') (and perhaps the same for stderr) when you open the subprocess.

Devin Jeanpierre
+4  A: 

If you have Python 2.4, you can use the subprocess module:

>>> import subprocess
>>> s = subprocess.Popen(['cowsay', 'hello'], \
      stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
>>> print s
 _______ 
< hello >
 ------- 
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
Manuel
I tried this and it worked, thanks!
Lin
A: 
import os
import subprocess

fnull = open(os.devnull, 'w')
result = subprocess.call('A', shell = True, stdout = fnull, stderr = fnull)
fnull.close()
DNS
why is shell = True?
Devin Jeanpierre
Because the original question used os.system and, not knowing exactly what he's doing, shell = True is the most reliable translation for that.
DNS
DNS, I tried your solution and it works perfectly for me. Thanks!
Lin
So? Tons of people use os.system() without realizing that they need not go through the shell. And now, since you didn't offer the more secure alternative, he's using shell=True, possibly without any good reason whatsoever.
Devin Jeanpierre
A: 

I know it's late to the game, but why not simply redirect output to /dev/null from within os.system? E.g.:

tgt_file = "./bogus.txt"
os.sytem("d2u '%s' &> /dev/null" % tgt_file)

This seems to work for those occasions when you don't want to deal with subprocess.STDOUT.

Rob Carr
A: 

If your search engine lead you to this old question (like me), be aware that Manuel's solution (at this time the most valued), namely using PIPE can lead to deadlocks.

Indeed, because pipes are buffered, you can write a certain number of bytes in a pipe, even if no one read it. However the size of buffer is finite. And consequently if your program A has an output larger than the buffer, A will be blocked on writing, while the calling program B awaits the termination of A.

So, I recommend using Devin Jeanpierre and DNS' solution.

Po' Lazarus