【问题标题】:Python Curses - module 'curses' has no attribute 'LINES'Python Curses - 模块'curses'没有属性'LINES'
【发布时间】:2015-04-09 23:50:01
【问题描述】:

我正在查看一本书中的一些源代码,并注意到某些代码似乎不在当前的 Python2.7 API 中。根据这段代码,模块curses 应该有一个名为LINES 的常量变量和另一个名为COLS 的常量变量。我打开一个Python交互终端,看到没有COLSLINES变量或方法。

我的问题是:这段代码是如何工作的?

def draw_loglines(self):
        self.screen.clear()
        status_col = 4
        bytes_col = 6 
        remote_host_col = 20
        status_start = 0 
        bytes_start = 4 
        remote_host_start = 10
        line_start = 26 
        logline_cols = curses.COLS - status_col - bytes_col - remote_host_col - 1
        for i in range(curses.LINES):
            c = self.curr_topline
            try:
                curr_line = self.loglines[c]
            except IndexError:
                break
            self.screen.addstr(i, status_start, str(curr_line[2]))
            self.screen.addstr(i, bytes_start, str(curr_line[3]))
            self.screen.addstr(i, remote_host_start, str(curr_line[1]))
            #self.screen.addstr(i, line_start, str(curr_line[4])[logline_cols])
            self.screen.addstr(i, line_start, str(curr_line[4]), logline_cols)
            self.curr_topline += 1 
        self.screen.refresh()

【问题讨论】:

    标签: python python-2.7 python-curses


    【解决方案1】:

    我发现curses.LINES存在于Python2 & Python3中,但是你必须在使用它之前调用curses.initscr,否则你会得到AttributeError。

    你也可以使用window.getmaxyx

    [1]https://docs.python.org/2/library/curses.html#curses.window.getmaxyx

    【讨论】:

    • 不,它不一样:curses.LINES 是一个常量,显示默认编号。行数,它与窗口设置无关,而window.getmaxyx() 是一个函数,并且没有。它返回的行数可能与默认行不同,如果它应用于创建的窗口,例如curses.newwin().
    【解决方案2】:

    该代码是为 Python 3 编写的。您可以看到 curses.LINES 现在在该 API 中,尽管它不在 Python 2.7 中:

    https://docs.python.org/3/howto/curses.html

    如果您需要在 Python 2 中获取终端宽度和高度,请参见此处:How to get Linux console window width in Python

    【讨论】:

    • 如果我打开 Python3 交互式 shell 并导入 curses 然后输入 curses.LINES 我仍然收到错误。 :/ 谢谢你的回复。
    • 天哪,我刚刚尝试了Python 3.3,你是对的,它不起作用。也许是 3.4?
    • 我正在使用 Python 3.2.3 :/ 我可能必须尝试升级。我正在阅读的书出版于 2008 年,所以我怀疑他们使用的是 Python 3000。:D 感谢约翰的帮助。您链接的关于终端宽度和高度的 SO 线程可能是我最好的选择。
    • wong2 的回答是正确的。链接的文档是教程,而不是 API 文档,因此这些变量在两个版本中都没有记录。请注意,由于它们仅在 initscr 之后添加,因此您无法通过 from curses import * 获取它们。当终端调整大小时,它们似乎会动态更新(对于 PEP8 来说如此之多,这表明大写是常量)。
    猜你喜欢
    • 2013-06-28
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    相关资源
    最近更新 更多