<p>仅供参考。
为了以最简单的方式解决这个问题,我只编写了自己的函数来完成<a href="http://docs.python.org/library/curses.html#curses.window.getstr" rel="nofollow">getstr()</a>所做的事情和一些。它不会在出现错误时退出。欢迎所有评论、更正、优化。在</p>
<pre><code>'''
Function to read a string from the current cursor position.
It supports some simple editing: Ctrl+A, Ctrl+E, Backspace, Del, Home, End,
'''
def getstr(window, prompt = "> ", end_on_error = False):
result = ""
starty, startx = window.getyx()
window.move(starty, 0)
window.deleteln()
window.addstr(prompt)
window.refresh()
window.keypad(True)
starty, startx = window.getyx()
endy, endx = window.getyx()
maxy, maxx = window.getmaxyx()
while True:
try:
selection = -1
while (selection < 0 and end_on_error == False):
selection = window.getch()
except:
e = sys.exc_info()[0]
window.addstr("<p>Error: %s</p>" % e)
break
if (selection == curses.KEY_ENTER or selection == ord('\n')):
break
elif (selection == curses.KEY_HOME or selection == 1):
window.move(starty, startx)
continue
elif (selection == curses.KEY_END or selection == 5):
window.move(endy, endx)
continue
elif (selection == curses.KEY_DC):
cy, cx = window.getyx()
window.delch()
result = result[:(cx - startx)] + result[(cx - startx + 1):]
endx -= 1
continue
elif (selection == curses.KEY_LEFT):
cy, cx = window.getyx()
if (cx > startx):
window.move(cy, cx-1)
continue
elif (selection == curses.KEY_RIGHT):
cy, cx = window.getyx()
if (cx < endx):
window.move(cy, cx+1)
continue
elif (selection == curses.KEY_BACKSPACE or selection == 127):
cy, cx = window.getyx()
if (cx == startx):
# no more to backspace
continue
else:
window.move(cy, cx-1)
window.delch()
endx -= 1
cx -= 1
result = result[:(cx - startx)] + result[(cx - startx + 1):]
continue
else:
endy, endx = window.getyx()
if (selection < 256 and endx+1 < maxx):
result = result[:(endx - startx)] + chr(selection) + result[(endx - startx):]
window.addstr(result[(endx - startx):])
window.move(endy, endx+1)
endy, endx = window.getyx()
window.keypad(False)
output(result)
return result
</code></pre>