简体   繁体   English

按下 ctrl+C 时如何不停止程序?

[英]How can I not stop the program when ctrl+C is pressed?

I am trying to not stop the program when the user press Ctrl + C .当用户按下Ctrl + C时,我试图不停止程序。

Now it's like this:现在是这样的:

(programm running)
...
(user press ctrl+c)
You pressed ctrl+c
breaks

What I want is:我想要的是:

(programm running)
...
(user press ctrl+c)
You pressed ctrl+c
not breaks

How can I do this?我怎样才能做到这一点? Is it impossible?这是不可能的吗?

I tried this code:我试过这段代码:

try:
    while True: 
        userinput = input()
        if userinput == "stop":
            break
except (KeyboardInterrupt, SystemExit):
    print('You pressed ctrl+c')

I tried adding pass to except , but It doesn't give the expected output.我尝试将pass添加到except ,但它没有给出预期的 output。

Move it inside the loop as I'm guessing you want to continue looping instead of exiting:将它移动到循环内,因为我猜你想继续循环而不是退出:

while True:
    try:
        userinput = input()
        if userinput == "stop":
            break
    except (KeyboardInterrupt, SystemExit):
        print('You pressed ctrl+c')
        # or just pass to print nothing

you can easily implement the next step within the try & except or set a pass after it.您可以轻松地在 try & except 中实现下一步,或者在它之后设置一个pass

while True:
    try:
        userinput = input()
        if userinput == "stop":
            break
    except (KeyboardInterrupt, SystemExit):
        # or edit it to the next state in the program.
        pass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当按下Ctrl + c时,如何以干净的方式杀死python程序(包括ROS和扭曲协议)? - How to kill a python program (which includes ROS and twisted protocol) in a clean way when Ctrl+c is pressed? 在python中按下CTRL + C时如何优雅地终止循环 - How to terminate loop gracefully when CTRL+C was pressed in python 如何在不调用 KeyboardInterrupt 的情况下按顺序按 ctrl+c 停止代码执行? - How can I stop code execution by sequentially pressing ctrl+c without calling KeyboardInterrupt? 在python中,如何在终端中按Ctrl + C时阻止显示“ ^ C”? - In python, how can I prevent the “^C” from showing up when I press Ctrl+C in the terminal? 如何在 python3.8 中检测 CTRL+C? - How can i detect CTRL+C in python3.8? 如何注册将在按下Ctrl + C后立即运行的SIGINT处理程序? - How to register a SIGINT handler that will run as soon as Ctrl+C is pressed? 在Python中,为什么控制台输出有时会暂停,直到按ctrl-c为止,我该如何停止呢? - In Python, why does console output occasionally pause until ctrl-c is pressed, and how can I stop this? 带线程的Python程序无法捕获CTRL + C. - Python program with thread can't catch CTRL+C 按下CTRL + C时如何防止显示^ C - How do I prevent ^C from showing when displayed when pressing CTRL+C 使用Ctrl + C杀死Python作业会发生什么? 我可以强制自动保存吗? - What happens when a Python job is killed with Ctrl+C? Can I force an automatic save?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM