2011-10-22 73 views
3

我使用python的cmd模块实现了一个简单的shell。
现在,我想实现这个壳UNIX管道,那就是当我键入:用python cmd模块实现unix管道?

ls | grep "a" 

会的do_ls结果传递到do_grep输入,
什么是最简单的方式做这个?
对不起CryptoJones,我忘了说我的平台是Windows。

回答

2

举个简单的例子,可以帮助你:

from cmd import Cmd 

class PipelineExample(Cmd): 

    def do_greet(self, person): 
     if person: 
      greeting = "hello, " + person 
     else: 
      greeting = 'hello' 
     self.output = greeting 

    def do_echo(self, text): 
     self.output = text 

    def do_pipe(self, args): 
     buffer = None 
     for arg in args: 
      s = arg 
      if buffer: 
       # This command just adds the output of a previous command as the last argument 
       s += ' ' + buffer 
      self.onecmd(s) 
      buffer = self.output 

    def postcmd(self, stop, line): 
     if hasattr(self, 'output') and self.output: 
      print self.output 
      self.output = None 
     return stop 

    def parseline(self, line): 
     if '|' in line: 
      return 'pipe', line.split('|'), line 
     return Cmd.parseline(self, line) 

    def do_EOF(self, line): 
     return True 

if __name__ == '__main__': 
    PipelineExample().cmdloop() 

下面是一个例子会话:

(Cmd) greet wong 
hello, wong 
(Cmd) echo wong | greet 
hello, wong 
(Cmd) echo wong | greet | greet 
hello, hello, wong 
2

最简单的方法可能是您的do_ls的输出存储在缓冲区中,并喂以do_grep。您可能希望逐行或逐行执行,而不是一次执行,特别是如果您要执行more命令。

更完整的方法是在子进程中运行所有的命令,并依靠现有的标准库模块来支持管道, subprocess