6

在 Python 中,我想同时使用 cmd 和 curses 编写一个终端程序,即。使用 cmd 接受和解码完整的输入行,但使用 curses 定位输出。

像这样将 curses 和 cmd 的示例混合在一起:

import curses 
import cmd

class HelloWorld(cmd.Cmd):
    """Simple command processor example."""

    def do_greet(self, line):
        screen.clear()
        screen.addstr(1,1,"hello "+line)
        screen.addstr(0,1,">")
        screen.refresh()

    def do_q(self, line):
        curses.endwin()
        return True

if __name__ == '__main__':
    screen = curses.initscr()   
    HelloWorld().cmdloop()

我发现我在打字时什么都看不到。curses 大概是在屏幕上显示任何内容之前等待刷新。我可以切换到使用 getch() 但是我会失去 cmd 的值。

有没有办法让这些一起工作?

4

1 回答 1

1

这个问题似乎很老了......但它引起了足够的关注,所以我想把我的答案抛在脑后..你可以在这里查看该网站并清除你的疑虑..

更新:这个答案链接到原始提问者的要点。只是为了节省必须点击链接的人......这是完整的代码:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import curses 
import curses.textpad
import cmd

def maketextbox(h,w,y,x,value="",deco=None,textColorpair=0,decoColorpair=0):
    # thanks to http://stackoverflow.com/a/5326195/8482 for this
    nw = curses.newwin(h,w,y,x)
    txtbox = curses.textpad.Textbox(nw,insert_mode=True)
    if deco=="frame":
        screen.attron(decoColorpair)
        curses.textpad.rectangle(screen,y-1,x-1,y+h,x+w)
        screen.attroff(decoColorpair)
    elif deco=="underline":
        screen.hline(y+1,x,underlineChr,w,decoColorpair)

    nw.addstr(0,0,value,textColorpair)
    nw.attron(textColorpair)
    screen.refresh()
    return nw,txtbox

class Commands(cmd.Cmd):
    """Simple command processor example."""
        
    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = "> "
        self.intro  = "Welcome to console!"  ## defaults to None
    
    def do_greet(self, line):
        self.write("hello "+line)

    def default(self,line) :
        self.write("Don't understand '" + line + "'")

    def do_quit(self, line):
        curses.endwin()
        return True

    def write(self,text) :
        screen.clear()
        textwin.clear()
        screen.addstr(3,0,text)
        screen.refresh()


if __name__ == '__main__':
    screen = curses.initscr()   
    curses.noecho()
    textwin,textbox = maketextbox(1,40, 1,1,"")
    flag = False
    while not flag :
        text = textbox.edit()
    curses.beep()
    flag = Commands().onecmd(text)
于 2017-01-03T14:02:48.210 回答