在Python中延迟键盘中断程序的重要部分



延迟程序重要部分的键盘中断的方法是什么(在我的示例中)。

我想下载(或保存)许多文件,如果花费太长时间,我想完成该程序。

需要使用信号模块,如答案中的捕获键盘间断而没有试验?我可以通过信号处理程序设置一个全局变量,并在周期中打破循环吗?

原始周期是:

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

类似以下内容可能有效:

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

最新更新