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

2024-03-28 14:50:50 发布

您现在位置:Python中文网/ 问答频道 /正文

对于程序的一个重要部分,延迟键盘中断的方法是什么(在我的例子中是一个循环)。在

我想下载(或保存)许多文件,如果时间太长,我想在最近的文件下载完毕后完成程序。在

我需要使用信号模块作为in the answer for Capture keyboardinterrupt in Python without try-except?我可以用信号处理程序将全局变量设置为True并在为True时中断循环吗?在

原始循环为:

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

Tags: 模块文件the方法answerin程序true
1条回答
网友
1楼 · 发布于 2024-03-28 14:50:50

下面这样的方法可能有用:

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

相关问题 更多 >