Reading/writing to a Popen() subprocess

后端 未结 2 876
陌清茗
陌清茗 2021-02-07 20:26

I\'m trying to talk to a child process using the python subprocess.Popen() call. In my real code, I\'m implementing a type of IPC, so I want to write some data, read the respons

2条回答
  •  醉酒成梦
    2021-02-07 21:25

    sed's output is buffered and only outputs its data until enough has been cumulated or the input stream is exhausted and closed.

    Try this:

    import subprocess
    p = subprocess.Popen(["sed", 's/a/x/g'],
                         stdout = subprocess.PIPE,
                         stdin = subprocess.PIPE)
    
    p.stdin.write("abc\n")
    p.stdin.write("cat\n")
    p.stdin.close()
    
    print "Reading result 1:"
    print p.stdout.readline()
    
    print "Reading result 2:"
    print p.stdout.readline()
    

    Be aware that this cannot be done reliably which huge data as wriring to stdin blocks once the buffer is full. The best way to do is using communicate().

提交回复
热议问题