Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中延迟键盘中断是程序的一个重要部分_Python_Keyboardinterrupt - Fatal编程技术网

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

在Python中延迟键盘中断是程序的一个重要部分,python,keyboardinterrupt,Python,Keyboardinterrupt,延迟程序重要部分的键盘中断的方法是什么(在我的例子中是循环) 我想下载(或保存)很多文件,如果需要的时间太长,我想在下载最近的文件后完成程序 我需要将信号模块用作吗?我是否可以使用信号处理程序将全局变量设置为True,如果为True,则中断循环 最初的周期是: for file_ in files_to_download: urllib.urlretrieve("".join(baseurl, file_), os.path.join(".", file_)) 类似以下的方法可能会起

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

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

我需要将信号模块用作吗?我是否可以使用信号处理程序将全局变量设置为True,如果为True,则中断循环

最初的周期是:

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

类似以下的方法可能会起作用:

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

这很容易。我应该试试它,而不是问。@ArpadHorvath:如果您在一个包中有多个模块,您可以将信号处理程序捆绑在一个类中。将每个处理程序设置为
classmethod
,以便它可以轻松设置类属性,例如
cls.finish
。然后,例如,检查
SignalState。如果类名为
SignalState
,则在循环中完成
。我可以使用signal.signal(signal.SIGINT,signal.default\u int\u处理程序)设置中断的原始状态。我应该在重要部分之前设置我的处理程序,然后设置默认处理程序。我是对的吗?我根据F.J和eryksun的答案制作了一个模块:SafeInterruptHandler类有一个off和on类方法来切换特殊行为,还有一个decorator方法来创建安全函数。谢谢,很简单。我应该试试它,而不是问。@ArpadHorvath:如果您在一个包中有多个模块,您可以将信号处理程序捆绑在一个类中。将每个处理程序设置为
classmethod
,以便它可以轻松设置类属性,例如
cls.finish
。然后,例如,检查
SignalState。如果类名为
SignalState
,则在循环中完成
。我可以使用signal.signal(signal.SIGINT,signal.default\u int\u处理程序)设置中断的原始状态。我应该在重要部分之前设置我的处理程序,然后设置默认处理程序。我是对的吗?我根据F.J和eryksun的答案制作了一个模块:SafeInterruptHandler类有一个off和on类方法来切换特殊行为,还有一个decorator方法来创建安全函数。谢谢