سؤال

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_)) 
هل كانت مفيدة؟

المحلول

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_)) 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top