2009-02-06 35 views
8

我正在用cmd模塊對Python應用程序進行原型開發。使用python cmd模塊分頁

給用戶的一些消息會很長,我想給他們分頁。 消息的前10行(或可配置數字)會出現,按下空格鍵會顯示下一頁,直到消息結束。

我不想在這裏重新創造一些東西,有沒有簡單的意思來實現這個功能?

回答

4

簡單的事情就是在運行時通過「less」或類似命令來管理腳本。

這裏有一個簡單的方法是不約你想要什麼,但:

def print_and_wait(some_long_message): 
    lines = some_long_message.split('\n') 
    i=0 
    while i < len(lines): 
     print '\n'.join(lines[i:i+10]) 
     raw_input("press enter to read more...") 
     i += 10 

你也可以考慮使用詛咒。

+0

謝謝,但通過較少的管道會阻止交互,這是cmd模塊的目標。實現curses解決方案遠遠超出了我想用cmd模塊構建的初稿。 但是,您的print_and_wait解決方案是一個好的開始(雖然沒有工作,但是)。 – Gra 2009-04-02 08:25:53

3

正如Yoni所說的,正確的做法是提供一個打印方法,該方法可以在運行的cmd實例中自動打印頁面。 Cmd的構造函數需要stdin和stdout參數。這麼簡單的提供一個像stdout一樣工作的對象並且支持你的分頁打印方法。

class PagingStdOut(object): 
    def write(self, buffer, lines_before_pause=40): 
     # do magic paging here... 
0

尋呼子程序可以在genutils.py文件的IPython部分(參見page,或page_dumb更簡單的一個)。代碼有點複雜,但如果你想要移植到包括Windows和各種終端仿真器在內的系統,這可能是不可避免的。

+0

謝謝,我已經實現了我的分頁程序。我會看看我在你指出的文件中錯過了什麼。目前它在我的操作系統中工作,但我沒有測試其他任何東西,所以便攜式增強功能可能會有用。 – Gra 2009-04-02 08:33:12

1

我有同樣的問題。 pydoc module內置傳呼機。我把它整合到了它裏面(我覺得它有點ha and和不盡人意......儘管我有更好的想法)。

我喜歡這樣的想法,即如果有超過x結果和分頁打開,它可以自動分頁,這是可以實現的,但在這裏沒有完成。

import cmd 
from pydoc import pager 
from cStringIO import StringIO 
import sys 

PAGER = True 
class Commander(cmd.Cmd): 
    prompt = "> " 
    def do_pager(self,line): 
     global PAGER 
     line = line + " 1" 
     tokens = line.lower().split() 
     if tokens[0] in ("on","true","t", "1"): 
      PAGER = True 
      print "# setting PAGER True" 
     elif tokens[0] in ("off","false","f","0"): 
      PAGER = False 
      print "# setting PAGER False" 
     else: 
      print "# can't set pager: don't know -> %s" % tokens[0] 

    def do_demo(self,line): 
     results = dict(a=1,b=2,c=3) 
     self.format_commandline_results(results) 

    def format_commandline_results(self,results): 
     if PAGER: 
      ofh = StringIO() 
     else: 
      ofh = sys.stdout 

     for (k,v) in sorted(results.items()): 
      print >> ofh, "%s -> %s" % (k,v) 

     if PAGER: 
      ofh.seek(0) 
      pager(ofh.read()) 

     return None 

    def do_EOF(self,line): 
     print "", 
     return True 

if __name__ == "__main__": 
    Commander().cmdloop("# try: \n> pager off \n> demo \n> pager on \n> demo \n\n")