python - nodelay() 导致 python curses 程序退出

标签 python ncurses curses

我用 python 编写了一个 curses 程序。它运行良好。但是,当我使用 nodelay() 时,程序在终端启动后立即退出,什么也没有显示(只是一个新提示)。

编辑

此代码将重现错误:

sc = curses.initscr()

sc.nodelay(1) # But removing this line allows the program to run properly

for angry in range(20):
        sc.addstr(angry, 1, "hi")

这是我的完整代码

import curses, time, sys, random

def paint(x, y, i):
        #...
def string(s, y):
        #...

def feed():
        #...

sc = curses.initscr()
curses.start_color()
curses.curs_set(0)
sc.nodelay(1) #########################################

 # vars + colors inited

for angry in range(20):
        try:
                dir = chr(sc.getch())

                sc.clear()

                feed()

                #lots of ifs

                body.append([x, y])
                body.pop(0)

                for point in body:
                        paint(*point, i=2)

                sc.move(height-1, 1)
                sc.refresh()
                time.sleep(wait)

        except Exception as e:
                print sys.exc_info()[0], e

sc.getch()
curses.beep()

curses.endwin()

为什么会这样,我该如何安全地使用 nodelay()

最佳答案

我已经重写了您的缩小版演示,以使基本功能正常运行。它有一个非阻塞的 getch()。如果在调用 getch() 时按住 Q 键,则程序结束,否则循环继续。

import curses, time

def main(sc):
    sc.nodelay(1)

    for angry in range(20):
        sc.addstr(angry, 1, "hi")
        sc.refresh()

        if sc.getch() == ord('q'):
            break

        time.sleep(1)

if __name__=='__main__':
    curses.wrapper(main)

我做的最重要的改变是使用 curses.wrapper获取屏幕上下文而不是使用 curses.initscr()。好处是,如果您的程序遇到未捕获的异常(例如命中 ^C),它会撤消您对终端所做的所有更改,例如在退出前禁用光标。它在调试时很有帮助。

从这里我建议以非常小的步骤重新添加您的程序的功能。使用 Curses 是一种痛苦,如果您一次进行大量更改,则很难找出是哪一个导致了问题。祝你好运!

关于python - nodelay() 导致 python curses 程序退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14004835/

相关文章:

Python-在类函数内调用函数

ncurses 窗口中的光标不在所需位置

ruby - 如何让 Ruby curses 正确响应箭头键?

python - 使用 python +curses 重写一行

python - 为 Sendgrid 的电子邮件 API 编码 CSV 文件

python - 有条件替换 pandas 数据框中的对象

c++ - ncurses 中的 system() 输出

macos - NCurses 和 OS X 10.6 发生了什么变化?

python - _curses.error : add_wch() returned an error

php - 在 Web 服务器上处理长时间运行任务的最佳方式