[Tutor] "standard output: Broken pipe"

Martin Walsh mwalsh at groktech.org
Sat Oct 20 11:42:32 CEST 2007


James wrote:
> Hi,
> 
> I have a snippet of code in a Python script I'm whipping up that's  
> causing a not-so-pretty output.  Here's the code:
> 
> subprocess.call( "yes '' | make oldconfig" , shell=True )
> 
> When I run this code, Python loyally executes the command, and then I  
> see the following error on my console:
> 
> -----
> 
> yes: standard output: Broken pipe
> yes: write error
> 
> Thoughts / ideas?

File this one under 'wicked scary hack', but my first thought would be
to redirect stderr of 'yes' to /dev/null, while preserving stderr of
'make oldconfig'. Something like this:

import subprocess as sp
sp.call("yes '' 2> /dev/null | make oldconfig", shell=True)

... or ...

import subprocess as sp
p1 = sp.Popen("yes ''", shell=True, stdout=sp.PIPE,
         stderr=file('/dev/null', 'w'))
p2 = sp.Popen('make oldconfig', shell=True,
         stdin=p1.stdout)

However, since the 'equivalent' shell command doesn't seem to result in
a broken pipe error there must be a better way. Upon further inspection:

  $ strace yes 'Spam' | head -n 10
  <...>
  --- SIGPIPE (Broken pipe) @ 0 (0) ---
  +++ killed by SIGPIPE +++
  <...>

We may need to handle SIGPIPE. A quick search leads here:
http://article.gmane.org/gmane.comp.python.devel/88798/

... so, thanks to Mr. Woodcraft ...

import subprocess as sp
import signal
# warning: uses the system default action
# for SIGPIPE for all children, use subprocess
# preexec_fn arg if this is not desirable
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
sp.call("yes 'Spam' | head -n 10", shell=True)

HTH,
Marty


More information about the Tutor mailing list