我正在尝试为Python 2和3编写代码。这是我用来学习curses的完整代码:
# -*- coding: utf-8 -*-
from __future__ import print_function
import curses
import sys
import traceback
class Cursor(object):
def __init__(self):
self.stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
self.stdscr.keypad(True)
def end_window(self):
curses.nocbreak()
self.stdscr.keypad(False)
curses.echo()
curses.endwin()
def start_win(self, begin_x=0, begin_y=1, height=24, width=71):
return curses.newwin(height, width, begin_y, begin_x)
def applic():
print("yo man")
x = Cursor()
window = x.start_win()
try:
# This raises ZeroDivisionError when i == 10.
for i in range(0, 11):
v = i - 10
key = window.getch()
# EDIT - Added this debug line to verify what key gets
window.addstr('type of {} is {}\n'.format(key, type(key)))
if key == curses.KEY_UP:
return
window.addstr('10 divided by {} is {}\n'.format(v, 10 // v))
window.refresh()
except Exception:
x.end_window()
errorstring = sys.exc_info()[2]
traceback.print_tb(errorstring)
applic()
我的问题是key
永远不会等于curses.KEY_UP
,因为getch()(或getkey())返回单个字符串,而不是整个转义键代码等于KEY_UP({{1} })。因此,每次按下例程中的向上箭头时,程序都会循环显示关键代码\x1b]A
,\x1b
,[
的三个部分,并生成三行输出:
A
对于这个测试,我希望UP箭头键允许我在i等于10时发生的预期异常之前爆发。
根据Curses的python文档,10 divided by -10 is -1
10 divided by -9 is -2
10 divided by -8 is -2
应该允许返回整个密钥代码,但似乎不会这样做。
添加了一些调试打印输出信息,以显示返回的内容。无论我使用getch()还是getkey(),结果都是一样的;它返回一个字符串(文档表明将为getch返回一个整数):
stdscr.keypad(True)
答案 0 :(得分:2)
问题是您在主窗口上设置了keypad
属性,但是使用getch
从另一个窗口读取。此更改将使您的程序接受KEY_UP
:
--- curses-vs-keypad.py 2017/04/02 11:07:41 1.1
+++ curses-vs-keypad.py 2017/04/03 00:57:16
@@ -28,6 +28,7 @@
print("yo man")
x = Cursor()
window = x.start_win()
+ window.keypad(True)
try:
# This raises ZeroDivisionError when i == 10.
for i in range(0, 11):