문제

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