加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

用python cmd模块实现一个unix管道?

发布时间:2020-12-20 11:21:27 所属栏目:Python 来源:网络整理
导读:我使用 python的cmd模块实现了一个简单的shell. 现在,我想在这个shell中实现一个unix管道,就是当我输入: ls | grep "a" 它会将do_ls的结果传递给do_grep的输入, 最简单的方法是什么? 对不起CryptoJones,我忘了说我的平台是Windows. 解决方法 这是一个可以
我使用 python的cmd模块实现了一个简单的shell.
现在,我想在这个shell中实现一个unix管道,就是当我输入:

ls | grep "a"

它会将do_ls的结果传递给do_grep的输入,
最简单的方法是什么?
对不起CryptoJones,我忘了说我的平台是Windows.

解决方法

这是一个可以帮助您的简单示例:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读