Python subprocess.Popen blocks with shell and pipe -


running following command: yes | head -1, shell, outputs y. using python's subprocess module call shell hangs indefinitely:

import subprocess  arg = "yes | head -1" process = subprocess.popen(arg,     shell=true,     stdout=subprocess.pipe,     stderr=subprocess.pipe, )  print "command started: %d" % process.pid r = process.communicate() print "command ended: %s %s" % r 

killing process exogenously using kill not help, nor making child process it's session leader using preexec_fn=os.setsid.

what causing behavior, , there anyway can prevent it?

i'm running python 2.7.3 , /bin/sh gnu bash, version 3.2.48(1)-release (x86_64-apple-darwin12)

so turns out caused due known issue python not resetting signal handlers before exec in subprocess module.

this same problem causes 'yes' reporting error subprocess communicate(), except gnu yes, epipe returned write causes program abort, whereas bsd yes (which used on os x far can tell), return code of write not checked, without sigpipe, yes not terminate.

it can fixed backporting reset_signals code, in above linked question:

def restore_signals():     signals = ('sigpipe', 'sigxfz', 'sigxfsz')     sig in signals:         if hasattr(signal, sig):             signal.signal(getattr(signal, sig), signal.sig_dfl) 

then setting preexec_fn=restore_signals in popen call.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -