2016-04-03 81 views
4

我開始學習python中的curses。我在Mac上使用python 3.5。當我嘗試在左下角程序崩潰寫,出現以下錯誤:詛咒在右下角調用addch

$ python ex_curses.py 
[...] 
    File "ex_curses.py", line 19, in do_curses 
    screen.addch(mlines, mcols, 'c') 
    _curses.error: add_wch() returned ERR 

示例程序是:

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) 

我感覺我已經失去了一些東西明顯。但我不知道是什麼。

回答

1

這是預期的行爲(怪癖),因爲addch嘗試在添加字符後將換行到下一行。有一個comment in 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). 
*/ 
1

對於未來的讀者。在@Thomas Dickey回答後,我在代碼中添加了以下代碼片段。

try: 
    screen.addch(mlines, mcols, 'c') 
except _curses.error as e: 
    pass 

現在我的代碼如下所示:

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)