2013-01-21 16 views
7

我對curses很陌生,所以我在python中嘗試了一些不同的東西。使程序退出後在終端回滾歷史記錄中產生curses程序輸出

我已經初始化窗口併爲窗口對象設置了scrollok。我可以添加字符串,並且滾動工作,以便addstr()在窗口的末尾沒有任何錯誤。

我想要的是能夠在程序結束後在我的終端程序(tmux或KDE Konsole,在這種情況下)中滾動回程序輸出。

在我的代碼中,我至少可以看到輸出,如果我跳過endwin()調用,但終端需要重置調用才能恢復運行。

另外,即使在程序運行時,在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() 

回答

7

對於這個任務,我會建議你使用一個鍵盤(http://docs.python.org/2/library/curses.html#curses.newpad):

襯墊就像一個窗口,但它不是由屏幕大小的限制,而不是必然與屏幕的特定部分相關聯。 [...]只有一部分窗口會一次顯示在屏幕上。 [...]

爲了在完成使用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) 
相關問題