无限循环和用户输入作为终止
我有我的代码,它确实可以运行到无穷大。我想要的是,如果在unix命令窗口上,如果用户输入ctrl C,我希望程序完成当前循环,然后退出循环。所以我希望它中断,但我希望它完成当前循环。使用 ctrl C 可以吗?我应该寻找不同的输入吗?
I have my code and it does go run to infinity. What I want is that if on the unix command window if the user inputs a ctrl C, I want the program to finish the current loop it in and then come out of the loop. So I want it to break, but I want it to finish the current loop. Is using ctrl C ok? Should I look to a different input?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要正确且完全按照您的要求执行此操作有点复杂。
基本上,您想要捕获 Ctrl-C,设置一个标志,然后继续直到检查该标志的循环开始(或结束)。这可以使用
signal
模块来完成。幸运的是,有人已经这样做了,您可以使用示例中的代码 链接。编辑:根据您下面的评论,
BreakHandler
类的典型用法是: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: