【问题标题】:Python Ncurses printing a single char to positionPython Ncurses 打印单个字符到位置
【发布时间】:2012-09-05 23:42:27
【问题描述】:

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

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

代码:

(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()

【问题讨论】:

  • 你看到了什么错误,你期待什么,index是什么?
  • @hayden 刚刚更新,由于奇怪的原因,错误消息未显示,已清除。 index是动态的,从0到9,我没问题
  • 我的猜测是您使用的是 24 行(或 25 行)终端,所以当您访问 stdscr.move(24, 0) 时它会失败。输入一个 try/catch 并让它重置屏幕,然后在重新加注之前记录 x 和 y,这样你就可以看到发生了什么。

标签: python terminal ncurses curses


【解决方案1】:

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

这些例程在失败时返回 ERR,在成功完成时返回 OK(SVr4 仅指定“ERR 以外的整数值”)。

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

第一个似乎不太可能出现在 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 打印:

0 25 wmove() returned ERR

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

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

0 50 wmove() returned ERR

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

40 0 wmove() returned ERR

如果您想提前检查而不是在错误发生时尝试捕获错误,请尝试在窗口上调用getmaxyx();如果 y

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

【讨论】:

    猜你喜欢
    • 2019-07-06
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2016-04-04
    • 1970-01-01
    相关资源
    最近更新 更多