Blocking ctrl-c to os.popen() or os.system()

pythonhda pythonhda at yahoo.com.replacepythonwithlinux
Sun Jan 5 01:02:33 EST 2003


On Sat, 04 Jan 2003 21:34:27 -0800
Erik Max Francis <max at alcyone.com> wrote:

> Sandeep Gupta wrote:
> 
> > I am executing a command from python via os.popen().  While the
> > command is executing, if I type ctrl-c, the command receives the
> > interrupt.  I would like to block the ctrl-c from the command and I've
> > tried the following:
> > 
> > 1)Using python's signal module to ignore SIGINT.  This causes python
> > to ignore SIGINT, but a ctrl-c that is typed during the popen() call
> > still goes to the command.
> > 
> > 2)Adding "< /dev/null" to the os.popen() call.  This doesn't help.
> > 
> > 3)Using popen2() and immediately closing the stdin file.  This also
> > doesn't work.
> > 
> > Any suggestions would be greatly appreciated!
> 
> The problem here (which other responders failed to identify) is that
> it's the spawned program that's getting the INT signal, not the Python
> program launching it.  Signals are really independent of stdin/stdout,
> so that's why your redirection and file closing isn't helping.
> 
> Unfortunately, I don't think there's any pretty solution to your
> problem.  What you probably need to do is write a wrapper program that
> intercepts the INT signal and ignores it (presuming that's what you
> actually want to do).  This would be similar to the nohup program (which
> does something analogous, but for the HUP signal).
> 
> You can write a little script to do it, with bash, ksh, zsh, or
> varieties.  In zsh it would look like:
> 
> 	#!/bin/zsh -f
> 
> 	function TRAPINT () { }
> 
> 	"$@"
> 
> The other shells have similar mechanisms, I believe involving a trap
> builtin.
> 
> Unfortunately you're probably going to be forced to use a wrapper script
> for portability, since with os.popen (or os.system) you're not
> guaranteed which shell is going to get run, so you can't do the trapping
> inline.
> 
> Note that this won't stop other signals, such as TERM, and that nothing
> can stop KILL.
> 
> -- 
>  Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
>  __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
> /  \ War is a continuation of policy by other means.
> \__/ Karl von Clausewitz
>     CAGE / http://www.alcyone.com/pyos/cage/
>  A cellular automaton simulation system in Python.

How about using a thread?

>From the docs:

       Threads  interact strangely with interrupts: the KeyboardInterrupt
       exception  will  be  received  by  an  arbitrary thread. (When the
       signal module  is  available,  interrupts  always  go  to the main
       thread.)

So you would have something like this:

worker = newThread() 
worker.start() 
while worker.isAlive():
	try:
		worker.join() # should block here until the thread is done
	except KeyboardInterrupt:
		print "still running, hold on..."




More information about the Python-list mailing list