KeyboardInterrupt should not kill subprocess

Michael Goerz newsgroup898sfie at 8439.e4ward.com
Thu Feb 21 12:35:52 EST 2008


Hi,

I'm using subprocess.Popen() to run some background processes. However, 
the program is also supposed to catch CTRL+C keyboard interrupts for 
refreshs (i.e. a keyboard interrupt doesn't shut down the program).

But as it seems, a keyboard interrupt will automatically pass down to 
the subprocesses, causing them to abort. Is there a way that I can 
prevent the subprocesses from being canceled by a keyboard interrupt?

To clarify my question, here is a minimal example:

import subprocess
import os
import time
import sys

# is 'sleep' available on Win machines?
# use another dummy program if it isn't
p = subprocess.Popen(['sleep', '10'])

while True:
     try:
         time.sleep(1)
         pass # normal program procedure
         print "subprocess poll: " + str(p.poll())
     except KeyboardInterrupt:
         try:
             print("Hit Ctrl+C again to quit")
             time.sleep(1)
             print "Refreshing"
             pass # do some refresh stuff here
         except KeyboardInterrupt:
             sys.exit(0)

As you can see, after the refresh, p.poll() is '-2'. I'd want the 
subprocess to continue undisturbed, i.e. p.poll() would still return 'None'.


Thanks,
Michael



More information about the Python-list mailing list