gpt4 book ai didi

python - 使用 python curses 逐页滚动或逐行滚动

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:18 25 4
gpt4 key购买 nike

我正在尝试使用 python curses 将一些文本写入窗口。但是当我到达窗口的尽头时,我得到 addstr() returned ERR

如何逐页或逐行滚动输出。?如何绑定(bind)空格键或向下箭头?

这是我的代码:

try:
screen = curses.initscr()
screen.immedok(True)
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
screen.bkgd(curses.color_pair(2))
screen.scrollok(1)
screen.border(0)

p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
linenumber = 1
for line in getline(output):
if linenumber <= 2:
# First two lines are header, mark bold
screen.addstr(linenumber, 2, line, curses.color_pair(1)|curses.A_BOLD)
else:
screen.addstr(linenumber, 2, line)
linenumber += 1

screen.getch()
curses.endwin()

except Exception, e:
print "\n\033[1;91m[FAILED]\033[0m Interrupt ", e
logging.error(e, exc_info=True)
curses.endwin()

最佳答案

问题是您对 screen.addstr 的调用要求输入屏幕末尾的行号。考虑到您在屏幕上绘制的框,更好的方法是在框内创建一个新窗口(例如使用 curses.newwin)并在该窗口内编写 addstr 调用.

您的示例未按给定的方式编译。这是一个工作示例:

import curses
import logging
import subprocess
import sys

command = "ls -l /bin"
try:
screen = curses.initscr()
screen.immedok(True)
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_BLACK)
screen.bkgd(curses.color_pair(2))
screen.border(0)
boxed = curses.newwin(curses.LINES - 2, curses.COLS - 2, 1, 1)
boxed.scrollok(1)

p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
linenumber = 1
for line in output.split("\n"):
if linenumber <= 2:
# First two lines are header, mark bold
boxed.addstr(line, curses.color_pair(1)|curses.A_BOLD)
else:
boxed.addstr(line)
boxed.addch("\n")
linenumber += 1
boxed.getch()

screen.getch()
curses.endwin()

except Exception, e:
print "\n\033[1;91m[FAILED]\033[0m Interrupt ", e
logging.error(e, exc_info=True)

关于python - 使用 python curses 逐页滚动或逐行滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30795161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com