很久以前就问过这个问题,但我遇到了完全相同的问题。我想要一个使用 curses 的 Python 程序在 Windows 和 Linux 上运行。KeyboardInterrupt 在 Linux 但不是 Windows 上完全按预期工作。我尝试了所有的诅咒设置功能,但永远无法让 Ctrl+C 进入执行。
下面的代码似乎有效,但并不理想。到目前为止我找不到更好的方法。这种方法在 Windows 上的问题在于它不会中断。代码将在检查输入之前执行当前循环迭代中所做的任何工作。(它仍然可以在 Linux 上完美运行。)
import curses
import time
def Main(stdscr):
stdscr.addstr(0, 0, "Main starting. Ctrl+C to exit.")
stdscr.refresh()
try:
i = 0
while True:
i = i + 1
stdscr.addstr(1, 0, "Do work in loop. i=" + str(i))
stdscr.refresh()
time.sleep(1)
stdscr.nodelay(1) # Don't block waiting for input.
c = stdscr.getch() # Get char from input. If none is available, will return -1.
if c == 3:
stdscr.addstr(2, 0, "getch() got Ctrl+C")
stdscr.refresh()
raise KeyboardInterrupt
else:
curses.flushinp() # Clear out buffer. We only care about Ctrl+C.
except KeyboardInterrupt:
stdscr.addstr(3, 0, "Ctrl+C detected, Program Stopping")
stdscr.refresh()
finally:
stdscr.addstr(4, 0, "Program cleanup")
stdscr.refresh()
time.sleep(3) # This delay just so we can see final screen output
curses.wrapper(Main)
Linux 上的输出:
Main starting. Ctrl+C to exit.
Do work in loop. i=4
Ctrl+C detected, Program Stopping
Program cleanup
Windows 上的输出:
Main starting. Ctrl+C to exit.
Do work in loop. i=6
getch() got Ctrl+C
Ctrl+C detected, Program Stopping
Program cleanup