如何避免在处理 KeyboardInterrupt 后打印 ^C
今天早上,我决定在我的服务器程序中处理键盘中断并优雅地退出。我知道该怎么做,但我挑剔的自己并没有发现它足够优雅,以至于 ^C
仍然被打印。如何避免 ^C
被打印?
import sys
from time import sleep
try:
sleep(5)
except KeyboardInterrupt, ke:
sys.exit(0)
按 Ctrl+C 退出上面的程序并看到 ^C
被打印。我可以使用一些 sys.stdout
或 sys.stdin
魔法吗?
This morning I decided to handle keyboard interrupt in my server program and exit gracefully. I know how to do it, but my finicky self didn't find it graceful enough that ^C
still gets printed. How do I avoid ^C
getting printed?
import sys
from time import sleep
try:
sleep(5)
except KeyboardInterrupt, ke:
sys.exit(0)
Press Ctrl+C to get out of above program and see ^C
getting printed. Is there some sys.stdout
or sys.stdin
magic I can use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是你的 shell 做的事情,python 与它无关。
如果您将以下行放入
~/.inputrc
中,它将抑制该行为:当然,我假设您正在使用 bash,但情况可能并非如此。
It's your shell doing that, python has nothing to do with it.
If you put the following line into
~/.inputrc
, it will suppress that behavior:Of course, I'm assuming you're using bash which may not be the case.
这可以解决问题,至少在 Linux 中是这样
This will do the trick, at least in Linux
我不知道这是否是执行此操作的最佳方法,但我通过打印两个
\b
(退格转义序列)然后打印一个空格或一系列字符来解决该问题。这可能工作得很好I don't know if this is the best way of doing this, but I fix that problem by printing two
\b
(backspace escape sequence) and then a space or a series of characters. This might work fine