Python subprocess module, how do I give input to the first of series of piped commands?

前端 未结 3 1920
误落风尘
误落风尘 2020-12-10 07:52

I am trying to use Python\'s subprocess module. What I require is to send input to the first process whose output becomes the input of the second process. The situation is b

3条回答
  •  自闭症患者
    2020-12-10 08:29

    Hmm, why not mix in a bit of (ba)sh? :-)

    from subprocess import Popen, PIPE
    cproc = Popen('cat | grep line', stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
    out, err = cproc.communicate("this line has the word line in it")
    

    BEWARE though:

    • This only works on systems that use a Bourne Shell compatible shell (like most *nix'es)

    • Usign shell=True and putting user input in the command string is a bad idea, unless you escape the user input first. Read the subprocess docs -> "Frequently Used Arguments" for details.

    • This is ugly, non portable, non pythonic and so on...

    EDIT: There is no need to use cat though, if all you want to do is grep. Just feed the input directly to grep, or even better, use python regular expressions.

提交回复
热议问题