我有我的代码,它确实运行到无穷大。我想要的是,如果在 unix 命令窗口上,如果用户输入 ctrl C,我希望程序完成当前循环,然后退出循环。所以我希望它中断,但我希望它完成当前循环。使用 ctrl C 可以吗?我应该寻找不同的输入吗?
问问题
1001 次
1 回答
3
To do this correctly and exactly as you want it is a bit complicated.
Basically you want to trap the Ctrl-C, setup a flag, and continue until the start of the loop (or the end) where you check that flag. This can be done using the signal
module. Fortunately, somebody has already done that and you can use the code in the example linked.
Edit: Based on your comment below, a typical usage of the class BreakHandler
is:
ih = BreakHandler()
ih.enable()
for x in big_set:
complex_operation_1()
complex_operation_2()
complex_operation_3()
# Check whether there was a break.
if ih.trapped:
# Stop the loop.
break
ih.disable()
# Back to usual operation
于 2010-08-10T22:11:46.003 回答