程序退出后,使curses程序输出保留在终端回滚历史记录中

2024-01-09

我对诅咒很陌生,所以我正在尝试 python 中的一些不同的东西。

我已经初始化了窗口并为窗口对象设置了scrollok。我可以添加字符串,并且滚动可以正常工作,这样 addstr() 在窗口末尾不会出现任何错误。

我想要的是在程序完成后能够在终端程序(在本例中为 tmux 或 KDE Konsole)中向后滚动程序输出。

在我的代码中,如果我跳过 endwin() 调用,我至少可以看到输出,但是终端需要一个reset致电以恢复运行。

此外,即使程序正在运行,在curses 窗口向下滚动后,我也无法在Konsole 中向后滚动以查看初始输出。

#!/usr/bin/env python2
import curses
import time
win = curses.initscr()
win.scrollok(True)
(h,w)=win.getmaxyx()
h = h + 10
while h > 0:
    win.addstr("[h=%d] This is a sample string.  After 1 second, it will be lost\n" % h)
    h = h - 1
    win.refresh()
    time.sleep(0.05)
time.sleep(1.0)
curses.endwin()

对于此任务,我建议您使用垫(http://docs.python.org/2/library/curses.html#curses.newpad http://docs.python.org/2/library/curses.html#curses.newpad):

pad 就像一个窗口,只不过它不受屏幕尺寸的限制,并且不一定与屏幕的特定部分相关联。 [...] 屏幕上一次只会显示窗口的一部分。 [...]

为了在使用完 Curses 后将 pad 的内容保留在控制台上,我会从 pad 读回内容,结束 curses 并将内容写入标准输出。

以下代码实现了您所描述的效果。

#!/usr/bin/env python2

import curses
import time

# Create curses screen
scr = curses.initscr()
scr.keypad(True)
scr.refresh()
curses.noecho()

# Get screen width/height
height,width = scr.getmaxyx()

# Create a curses pad (pad size is height + 10)
mypad_height = height + 10
mypad = curses.newpad(mypad_height, width);
mypad.scrollok(True)
mypad_pos = 0
mypad_refresh = lambda: mypad.refresh(mypad_pos, 0, 0, 0, height-1, width)
mypad_refresh()

# Fill the window with text (note that 5 lines are lost forever)
for i in range(0, height + 15):
    mypad.addstr("{0} This is a sample string...\n".format(i))
    if i > height: mypad_pos = min(i - height, mypad_height - height)
    mypad_refresh()
    time.sleep(0.05)

# Wait for user to scroll or quit
running = True
while running:
    ch = scr.getch()
    if ch == curses.KEY_DOWN and mypad_pos < mypad_height - height:
        mypad_pos += 1
        mypad_refresh()
    elif ch == curses.KEY_UP and mypad_pos > 0:
        mypad_pos -= 1
        mypad_refresh()
    elif ch < 256 and chr(ch) == 'q':
        running = False

# Store the current contents of pad
mypad_contents = []
for i in range(0, mypad_height):
    mypad_contents.append(mypad.instr(i, 0))

# End curses
curses.endwin()

# Write the old contents of pad to console
print '\n'.join(mypad_contents)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

程序退出后,使curses程序输出保留在终端回滚历史记录中 的相关文章

随机推荐