使用python cmd模块实现unix管道?
我正在使用python的使用python cmd模块实现unix管道?,python,windows,shell,cmd,pipe,Python,Windows,Shell,Cmd,Pipe,我正在使用python的cmd模块实现一个简单的shell。 现在,我想在这个shell中实现一个unix管道,也就是我键入: ls | grep "a" 它将把do_ls的结果传递给do_grep的输入, 最简单的方法是什么? 对不起,我忘了说我的平台是Windows。使用内置管道功能,而不是cmd 最简单的方法可能是将do\u ls的输出存储在缓冲区中,然后将其馈送到do\u grep。您可能希望一行一行地或一组行地执行此操作,而不是一次执行,尤其是如果您希望实现more命令 更完整的
cmd
模块实现一个简单的shell。现在,我想在这个shell中实现一个unix管道,也就是我键入:
ls | grep "a"
它将把do_ls
的结果传递给do_grep
的输入,最简单的方法是什么?
对不起,我忘了说我的平台是Windows。使用内置管道功能,而不是cmd
最简单的方法可能是将
do\u ls
的输出存储在缓冲区中,然后将其馈送到do\u grep
。您可能希望一行一行地或一组行地执行此操作,而不是一次执行,尤其是如果您希望实现more
命令
更完整的方法是在子进程中运行所有命令,并依赖现有的标准库模块进行管道支持,例如,您可能需要使用该模块。它是带有附加功能的cmd
的替代品
请参阅其文档部分。以下是一个简单的示例,可以帮助您:
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