Python Ncurses打印一个char来定位

Mus*_*afa 1 python curses terminal ncurses

我不是那么做ncurses,但它应该在C上工作,我不知道出了什么问题,我只是想连续打印一些字符到屏幕但是我找不到如何修复这个错误:

    File "capture.py", line 37, in <module>
     stdscr.move(y,x)
    _curses.error: wmove() returned ERR  
Run Code Online (Sandbox Code Playgroud)

码:

(irrelevant parts of the code are removed)
import curses

stdscr = curses.initscr()
curses.noecho();

palette = [' ', ' ', '.', '.', '/', 'c', '(', '@', '#', '8']

# index is something between 0 and len(palette), not important 
for x in xrange(50):
    for y in xrange(30):
        stdscr.move(y,x)
        sdtscr.addch(palette[index])
stdscr.refresh()
Run Code Online (Sandbox Code Playgroud)

aba*_*ert 5

如果您阅读了curses move的文档(例如,http://linux.die.net/man/3/move):

这些例程在失败时返回ERR并且在成功完成后确定(SVr4仅指定"除ERR之外的整数值").

具体来说,如果窗口指针为空,或者位置在窗口之外,它们将返回错误.

第一个似乎不太可能出现在Python中,所以第二个可能是你的问题.快速测试表明,运行代码可以在30行或更高的终端上正常工作,但在典型的24行或25行终端上运行失败.

如果你想让它更容易调试,首先将整个东西包装在try/中finally: curses.endscr()(这样你的终端就不会乱七八糟,可能无法看到输出).然后将调用包装在记录x和y stdscr.move的try/中except:,以便知道它失败的位置.我还将"30"变成命令行参数,以便更快地进行测试.这是包含所有这些更改的版本:

#!/usr/bin/python

import sys
import curses

height = int(sys.argv[1]) if len(sys.argv) > 1 else 24

try:
    stdscr = curses.initscr()
    curses.noecho();

    palette = [' ', ' ', '.', '.', '/', 'c', '(', '@', '#', '8']

    index = 0
    for x in xrange(50):
        for y in xrange(height):
            index = (index + 1) % len(palette)
            try:
                stdscr.move(y,x)
            except Exception as e:
                stdscr.refresh()
                curses.endwin()
                print
                print x, y, e
                sys.exit(1)
            stdscr.addch(palette[index])
    stdscr.refresh()
finally:
    curses.endwin()
Run Code Online (Sandbox Code Playgroud)

现在python cursetest 30打印:

0 25 wmove() returned ERR
Run Code Online (Sandbox Code Playgroud)

所以,正如我所怀疑的那样,它在x = 0,y = 25时失败了.

如果我将终端扩展到80x50,它可以工作,但现在python cursetest 60失败了:

0 50 wmove() returned ERR
Run Code Online (Sandbox Code Playgroud)

就此而言,如果我将终端缩小到40x50,则python cursetest 30在水平边缘而不是垂直边缘处失败:

40 0 wmove() returned ERR
Run Code Online (Sandbox Code Playgroud)

如果你想提前检查这个,而不是在发生错误时尝试捕获错误,请尝试调用getmaxyx()窗口; 如果y <30,你可以显示一个很好的错误信息并退出(或做一些不同的事情,或其他什么).

最后,快速检查表明这在C中也不起作用.当然没有异常抛出,如果你愿意,你可以忽略返回的错误,但你最终会连续300次写入位置(24,49).(如果你真的想要的话,你可以在Python中通过try/catch/pass来做同样的事情.)