5

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_)) 

1 Answer 1

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_)) 
Sign up to request clarification or add additional context in comments.

4 Comments

It is easy. I should try it instead of ask.
@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.
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?
I made a module based upon the answer of F.J and eryksun: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.