Gio*_*nni 9 python ncurses python-curses
我开始学习Python中的curses.我在Mac OS X上使用Python 3.5.当我尝试在右下角写入时,程序崩溃并出现以下错误:
$ python ex_curses.py
[...]
File "ex_curses.py", line 19, in do_curses
screen.addch(mlines, mcols, 'c')
_curses.error: add_wch() returned ERR
Run Code Online (Sandbox Code Playgroud)
示例程序是:
import curses
def do_curses(screen):
curses.noecho()
curses.curs_set(0)
screen.keypad(1)
(line, col) = 12, 0
screen.addstr(line, col, "Hello world!")
line += 1
screen.addstr(line, col, "Hello world!", curses.A_REVERSE)
screen.addch(0, 0, "c")
(mlines, mcols) = screen.getmaxyx()
mlines -= 1
mcols -= 1
screen.addch(mlines, mcols, 'c')
while True:
event = screen.getch()
if event == ord("q"):
break
curses.endwin()
if __name__ == "__main__":
curses.wrapper(do_curses)
Run Code Online (Sandbox Code Playgroud)
我有一种感觉,我错过了一些明显的东西,但我不知道是什么.
这是预期的行为(怪癖),因为在添加字符后addch尝试换行到下一行。lib_addch.c 中有一条评论处理这个问题:
/*
* The _WRAPPED flag is useful only for telling an application that we've just
* wrapped the cursor. We don't do anything with this flag except set it when
* wrapping, and clear it whenever we move the cursor. If we try to wrap at
* the lower-right corner of a window, we cannot move the cursor (since that
* wouldn't be legal). So we return an error (which is what SVr4 does).
* Unlike SVr4, we can successfully add a character to the lower-right corner
* (Solaris 2.6 does this also, however).
*/
Run Code Online (Sandbox Code Playgroud)
对于未来的读者。在 @Thomas Dickey 回答之后,我将以下代码片段添加到我的代码中。
try:
screen.addch(mlines, mcols, 'c')
except _curses.error as e:
pass
Run Code Online (Sandbox Code Playgroud)
现在我的代码如下所示:
import curses
import _curses
def do_curses(screen):
curses.noecho()
curses.curs_set(0)
screen.keypad(1)
(line, col) = 12, 0
screen.addstr(line, col, "Hello world!")
line += 1
screen.addstr(line, col, "Hello world!", curses.A_REVERSE)
screen.addch(0, 0, "c")
(mlines, mcols) = screen.getmaxyx()
mlines -= 1
mcols -= 1
try:
screen.addch(mlines, mcols, 'c')
except _curses.error as e:
pass
while True:
event = screen.getch()
if event == ord("q"):
break
curses.endwin()
if __name__ == "__main__":
curses.wrapper(do_curses)
Run Code Online (Sandbox Code Playgroud)