4

I'm implement a simple shell using python's cmd module.
Now, I'd like to implement a unix pipe in this shell, that is when I type:

ls | grep "a"  

it will pass the result of do_ls to the input of do_grep,
what's the simplest way to do this?
Sorry CryptoJones, I forgot to say that my platform is Windows.

4 Answers 4

3

Here is a simple example which could help you:

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()

Here is an example session:

(Cmd) greet wong
hello, wong
(Cmd) echo wong | greet
hello, wong
(Cmd) echo wong | greet | greet
hello, hello, wong
Sign up to request clarification or add additional context in comments.

Comments

2

The simplest way is probably to store the output of your do_ls in a buffer and feed it to do_grep. You probably want to do it line by line or by groups of lines, rather than in a single go, especially if you want to implement a more command.

A more complete approach would be to run all of your commands in sub-processes and rely on an existing standard library module for pipe support, e.g. subprocess.

Comments

2

You may want to use the cmd2 module. It is a replacement for cmd with additional features.

See the Output redirection section of its documentation.

Comments

1

Use the built in pipe function, not cmd.

http://docs.python.org/library/pipes.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.