问题
I have code that looks like this:
stdscr.nodelay(1)
while True:
c = stdscr.getch()
if c != -1:
stdscr.addstr("%s was pressed\n" % c)
if time() - last > 1:
stdscr.addstr("time() == %s\n" % str(time()))
last = time()
However, I'm worried that my code is really wasteful/inefficient. Is there a callback mechanism available for curses? If not, what would be the canonical way to handle this kind of situation?
回答1:
You could try Urwid instead.
Urwid provides a higher-level toolkit on top of curses and includes an event loop to handle keyboard and mouse input. It either uses it's own select-based event loop, or can hook into gevent or Twisted.
In addition to handling keyboard input efficiently you'll also have a host of options to handle user input with edit boxes, list controls and more.
回答2:
How about using half-delay mode to make getch() blocking?
import time
import curses
stdscr = curses.initscr()
curses.halfdelay(10) # 10/10 = 1[s] inteval
try:
while True:
c = stdscr.getch()
if c != -1:
stdscr.addstr("%s was pressed\n" % c)
stdscr.addstr("time() == %s\n" % time.time())
finally:
curses.endwin()
来源:https://stackoverflow.com/questions/10798211/callbacks-with-python-curses