3

What is the method to delay the keyboard interrupt for an important part of the program (in my example in a cycle).

I want to download (or save) many files, and if it takes too long, I want to finish the program, when the recent file have been downloaded.

Need I to use the signal module as in the answer for Capture keyboardinterrupt in Python without try-except? Can I set a global variable to True with the signal handler and break the cycle if it is True?

The original cycle is:

for file_ in files_to_download:
    urllib.urlretrieve("".join(baseurl, file_), os.path.join(".", file_)) 
Community
  • 1
  • 1

1 Answers1

5

Something like the following may work:

# at module level (not inside class or function)
finish = False
def signal_handler(signal, frame):
    global finish
    finish = True

signal.signal(signal.SIGINT, signal_handler)

# wherever you have your file downloading code (same module)
for file_ in files_to_download:
    if finish:
        break
    urllib.urlretrieve("".join(baseurl, file_), os.path.join(".", file_)) 
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • It is easy. I should try it instead of ask. – Arpad Horvath -- Слава Україні Nov 02 '12 at 16:55
  • 1
    @ArpadHorvath: If you have multiple modules in a package, you could bundle your signal handlers in a class. Make each handler a `classmethod` so it can easily set class attributes such as `cls.finish`. Then, for example, check `SignalState.finish` in your loop if the class is named `SignalState`. – Eryk Sun Nov 02 '12 at 20:09
  • I can set the original state for the interrupt with the signal.signal(signal.SIGINT, signal.default_int_handler). I should set my handler before the important part, and set the default handler after that. Am I right? – Arpad Horvath -- Слава Україні Nov 03 '12 at 00:02
  • 2
    I made a module based upon the answer of F.J and eryksun: https://gist.github.com/4006374 The SafeInterruptHandler class has an off and on classmethod to swich off and on the special behaviour, and a decorator method to create safe functions. Thanks. – Arpad Horvath -- Слава Україні Nov 03 '12 at 07:11