I'm experiencing problems with the getch() function of the curses library. Suppose we have the following program:

import curses

def main(stdscr):
    while 1:
        c = stdscr.getch()
        stdscr.addstr(chr(c) + ": " + str(c) + "\n")
curses.wrapper(main)

Let's run this, and enter the following characters: a, <backspace>, œ

Then the output is:

a: 97
ć: 263
Å: 197

As you see, the a character is taken correctly. However, the others are not. I just want to get the backspace '\b' and the unicode character œ, but we get something else.

Why does getch() behave this way, and how can I get the desired behaviour?

EDIT:

Let me emphasize that's it's not an issue with printing the characters, but with reading the characters. Namely, running stdscr.addstr('œ') indeed prints œ.

有帮助吗?

解决方案

In Python 3.3 the window.get_wch function was added. It handles all of those characters correctly.

If you read the documentation for window.getch, you'll notice that it doesn't claim to support non-ASCII printable characters. It just documents that it can handle non-ASCII key presses such as function keys or keypad keys.

EDIT:

When using window.get_wch, characters (e.g. 'a', 'ă', '好', '\n', or '\t') are returned as strings. Function keys are returned as integers (e.g. 265 or 274). Here is a new example to run. Try playing with the different keys you want to recognize to see how their values are returned. The format of the data printed is: [repr]: [type].

def main(stdscr):
    while 1:
        c = stdscr.get_wch()
        stdscr.addstr("%s: %s\n" % (repr(c), type(c)))

Here is what I get when I type in a, œ, <enter>, <backspace>, and <F1>:

'a': <class 'str'>
'œ': <class 'str'>
'\n': <class 'str'>
'\x7f': <class 'str'>
265: <class 'int'>

If an integer is returned, you can find out the name of the key pressed via curses.keyname:

>>> curses.keyname(265)
b'KEY_F(1)'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top