我有一个基本上有两个“线程”的重新设计的 python 诅咒代码。它们不是真正的线程——一个是主子窗口处理函数,第二个是不同的子窗口处理函数,在定时器上执行。我遇到了一个有趣的效果:
- 主窗口代码正在使用 getstr() 等待用户输入。
- 与此同时,定时器中断会到来,中断代码会在不同的子窗口中输出一些东西。
- 计时器函数的输出将导致 getstr() 返回空输入。
什么可能导致这种影响?除了检查返回字符串之外,还有什么方法可以避免这种影响?
重现问题的示例代码:
#!/usr/bin/env python
# Simple code to show timer updates
import curses
import os, signal, sys, time, traceback
import math
UPDATE_INTERVAL = 2
test_bed_windows = []
global_count = 0
def signal_handler(signum, frame):
global test_bed_windows
global global_count
if (signum == signal.SIGALRM):
# Update all the test bed windows
# restart the timer.
signal.alarm(UPDATE_INTERVAL)
global_count += 1
for tb_window in test_bed_windows:
tb_window.addstr(1, 1, "Upd: {0}.{1}".format(global_count, test_bed_windows.index(tb_window)))
tb_window.refresh()
else:
print("unexpected signal: {0}".format(signam))
pass
def main(stdscr):
# window setup
screen_y, screen_x = stdscr.getmaxyx()
stdscr.box()
# print version
version_str = " Timer Demo v:0 "
stdscr.addstr(0, screen_x - len(version_str) - 1, version_str)
stdscr.refresh()
window = stdscr.subwin(screen_y-2,screen_x-2,1,1)
for i in range(3):
subwin = window.derwin(3,12,1,2 + (15*i))
test_bed_windows.append(subwin)
subwin.box()
subwin.refresh()
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(UPDATE_INTERVAL)
# Output the prompt and wait for the input:
window.addstr(12, 1, "Enter Q/q to exit\n")
window.refresh()
the_prompt = "Enter here> "
while True:
window.addstr(the_prompt)
window.refresh()
curses.echo()
selection = window.getstr()
curses.noecho()
if selection == '':
continue
elif selection.upper() == 'Q':
break
else:
window.addstr("Entered: {0}".format(selection))
window.refresh()
if __name__ == '__main__':
curses.wrapper(main)