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

Jay*_*esh 9 python command-line command-line-interface

今天早上我决定在我的服务器程序中处理键盘中断并正常退出.我知道该怎么做,但我的挑剔的自我并没有发现它^C仍然得到印刷的优雅.如何避免^C打印?

import sys
from time import sleep
try:
  sleep(5)
except KeyboardInterrupt, ke:
  sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

按Ctrl + C退出上述程序并查看^C打印.我可以使用一些sys.stdoutsys.stdin魔法吗?

Chr*_*rle 8

这是你的shell,python与它无关.

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

set echo-control-characters off
Run Code Online (Sandbox Code Playgroud)

当然,我假设你正在使用bash,但可能并非如此.


小智 6

try:
    while True:
        pass
except KeyboardInterrupt:
    print "\r  "
Run Code Online (Sandbox Code Playgroud)

  • 更简洁:`sys.stderr.write("\r")` (3认同)

Die*_*ano 1

这可以解决问题,至少在 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)
Run Code Online (Sandbox Code Playgroud)