use*_*ser 5 python python-2.7 python-curses
我正在查看一本书中的一些源代码,并注意到某些代码似乎不在当前的 Python2.7 API 中。curses根据此代码,该模块应该有一个名为 的常量变量LINES和另一个名为COLS. 我打开一个Python交互式终端,看到没有COLS或LINES变量或方法。
我的问题是:这段代码是如何工作的?
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()
Run Code Online (Sandbox Code Playgroud)
我发现curses.LINES在Python2&Python3中存在,但是你必须curses.initscr在使用之前调用它,否则你会得到AttributeError。
你也可以使用 window.getmaxyx
[1] https://docs.python.org/2/library/curses.html#curses.window.getmaxyx
该代码是为 Python 3 编写的。您可以看到curses.LINES现在在该 API 中,尽管它不在 Python 2.7 中:
https://docs.python.org/3/howto/curses.html
如果您需要在Python 2中获取终端宽度和高度,请参阅此处:如何在Python中获取Linux控制台窗口宽度