blocks - send input to python subprocess pipeline

前端 未结 11 1327
轻奢々
轻奢々 2021-01-30 09:22

I\'m testing subprocesses pipelines with python. I\'m aware that I can do what the programs below do in python directly, but that\'s not the point. I just want to test the pipel

11条回答
  •  礼貌的吻别
    2021-01-30 09:56

    It's much simpler than you think!

    import sys
    from subprocess import Popen, PIPE
    
    # Pipe the command here. It will read from stdin.
    #   So cat a file, to stdin, like (cat myfile | ./this.py),
    #     or type on terminal and hit control+d when done, etc
    #   No need to handle this yourself, that's why we have shell's!
    p = Popen("grep -v not | cut -c 1-10", shell=True, stdout=PIPE)
    
    nextData = None
    while True:
        nextData = p.stdout.read()
        if nextData in (b'', ''):
            break
        sys.stdout.write ( nextData.decode('utf-8') )
    
    
    p.wait()
    

    This code is written for python 3.6, and works with python 2.7.

    Use it like:

    cat README.md  | python ./example.py
    

    or

    python example.py < README.md
    

    To pipe the contents of "README.md" to this program.

    But.. at this point, why not just use "cat" directly, and pipe the output like you want? like:

    cat filename | grep -v not | cut -c 1-10
    

    typed into the console will do the job as well. I personally would only use the code option if I was further processing the output, otherwise a shell script would be easier to maintain and be retained.

    You just, use the shell to do the piping for you. In one, out the other. That's what she'll are GREAT at doing, managing processes, and managing single-width chains of input and output. Some would call it a shell's best non-interactive feature..

提交回复
热议问题