Python Ncurses将单个字符打印到位置

2024-05-23 23:07:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

代码:

^{pr2}$

Tags: inpymove屏幕错误lineerror字符
1条回答
网友
1楼 · 发布于 2024-05-23 23:07:13

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

These routines return ERR upon failure and OK (SVr4 specifies only "an integer value other than ERR") upon successful completion.

Specifically, they return an error if the window pointer is null, or if the position is outside the window.

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

如果您想让调试更容易,首先将整个过程包装在一个try/finally:curses.endscr()(这样您的终端就不会一团糟,可能会导致无法看到输出)。然后将对stdscr.move的调用包装在一个记录x和y的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()

现在python cursetest 30打印:

^{pr2}$

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

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

0 50 wmove() returned ERR

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

40 0 wmove() returned ERR

如果您想预先检查这个问题,而不是在错误发生时试图捕捉错误,请尝试在窗口上调用getmaxyx();如果是y<;30,您可以显示一条很好的错误消息并退出(或执行其他操作,或其他任何操作)。在

最后,快速检查一下,这在C中也不起作用。当然,没有抛出异常,如果需要,可以忽略返回的错误,但最终只会连续写入300次position(24,49)。(如果你真的想要的话,你可以在Python中做同样的事情,在移动过程中执行try/catch/pass操作…)

相关问题 更多 >