如何避免在处理 KeyboardInterrupt 后打印 ^C

发布于 2024-12-07 06:07:50 字数 344 浏览 1 评论 0原文

今天早上,我决定在我的服务器程序中处理键盘中断并优雅地退出。我知道该怎么做,但我挑剔的自己并没有发现它足够优雅,以至于 ^C 仍然被打印。如何避免 ^C 被打印?

import sys
from time import sleep
try:
  sleep(5)
except KeyboardInterrupt, ke:
  sys.exit(0)

按 Ctrl+C 退出上面的程序并看到 ^C 被打印。我可以使用一些 sys.stdoutsys.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 技术交流群。

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

发布评论

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

评论(4

别理我 2024-12-14 06:07:50

这是你的 shell 做的事情,python 与它无关。

如果您将以下行放入 ~/.inputrc 中,它将抑制该行为:

set echo-control-characters off

当然,我假设您正在使用 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:

set echo-control-characters off

Of course, I'm assuming you're using bash which may not be the case.

丶情人眼里出诗心の 2024-12-14 06:07:50
try:
    while True:
        pass
except KeyboardInterrupt:
    print "\r  "
try:
    while True:
        pass
except KeyboardInterrupt:
    print "\r  "
花间憩 2024-12-14 06:07:50

这可以解决问题,至少在 Linux 中是这样

#! /usr/bin/env python
import sys
import termios
import copy
from time import sleep

fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = copy.deepcopy(old)
new[3] = new[3] & ~termios.ECHO

try:
  termios.tcsetattr(fd, termios.TCSADRAIN, new)
  sleep(5)
except KeyboardInterrupt, ke:
  pass
finally:
  termios.tcsetattr(fd, termios.TCSADRAIN, old)
  sys.exit(0)

This will do the trick, at least in Linux

#! /usr/bin/env python
import sys
import termios
import copy
from time import sleep

fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = copy.deepcopy(old)
new[3] = new[3] & ~termios.ECHO

try:
  termios.tcsetattr(fd, termios.TCSADRAIN, new)
  sleep(5)
except KeyboardInterrupt, ke:
  pass
finally:
  termios.tcsetattr(fd, termios.TCSADRAIN, old)
  sys.exit(0)
夜唯美灬不弃 2024-12-14 06:07:50

我不知道这是否是执行此操作的最佳方法,但我通过打印两个 \b (退格转义序列)然后打印一个空格或一系列字符来解决该问题。这可能工作得很好

if __name__ == "__main__":
    try:
        # Your main code goes here
    except KeyboardInterrupt:
        print("\b\bProgram Ended")

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

if __name__ == "__main__":
    try:
        # Your main code goes here
    except KeyboardInterrupt:
        print("\b\bProgram Ended")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文