无限循环和用户输入作为终止

发布于 2024-09-13 09:31:08 字数 124 浏览 2 评论 0原文

我有我的代码,它确实可以运行到无穷大。我想要的是,如果在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何时共饮酒 2024-09-20 09:31:08

要正确且完全按照您的要求执行此操作有点复杂。

基本上,您想要捕获 Ctrl-C,设置一个标志,然后继续直到检查该标志的循环开始(或结束)。这可以使用 signal 模块来完成。幸运的是,有人已经这样做了,您可以使用示例中的代码 链接

编辑:根据您下面的评论,BreakHandler 类的典型用法是:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文