I want to run a bunch of commands that take a while, but cannot be interrupted (firmware updates). I want to exit if a sigint was received earlier. I tried replacing signal.SIG_IGN with a class that counts each time a SIGINT was received, but after class iterates its counter the SIGINT still would go through to the main Python script.
Just ignoring it works pretty easily:
import subprocess
import signal
def dont_interrupt_me():
"""Run bash command."""
print "Keyboard interrupt ignored during update process."
# Stops keyboard interrupts during the Popen
sigint_stopper = signal.signal(signal.SIGINT, signal.SIG_IGN)
bash_cmd = subprocess.Popen(['sleep', '10'])
bash_cmd.wait()
install_return_code = bash_cmd.returncode
# Return signint to normal
signal.signal(signal.SIGINT, sigint_stopper)
# if ctrl_c_earlier:
# sys.exit(1)
return install_return_code
for each in range(1,10):
dont_interrupt_me()
My SigintIgnore class attempt not that doesn't work:
import subprocess
import signal
class SigintIgnore(object):
"""Count the number of sigint's during ignore phase."""
def __init__(self):
"""Init count to 0."""
self.count = 0
self.exit_amount = 10
def __call__(self, first, second):
"""Init count to 0."""
self.count += 1
print "\nself.count: " + str(self.count)
print "first: " + str(first)
print "second: " + str(second)
if self.count > 1:
print("Press 'ctrl + c' " +
str(self.exit_amount - self.count) +
" more times to force exit.")
if self.count > self.exit_amount:
sys.exit(EXIT_USER_CHOICE)
def dont_interrupt_me():
"""Run bash command."""
counter = SigintIgnore()
print "Keyboard interrupt ignored during update process."
sigint_stopper = signal.signal(signal.SIGINT, counter)
# Stops keyboard interrupts during the update calls
bash_cmd = subprocess.Popen(['sleep', '10'])
bash_cmd.wait()
install_return_code = bash_cmd.returncode
signal.signal(signal.SIGINT, sigint_stopper)
if counter.count > 1:
sys.exit(1)
return install_return_code
for each in range(1,10):
dont_interrupt_me()