blocks - send input to python subprocess pipeline

前端 未结 11 1483
轻奢々
轻奢々 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:52

    Here's an example of using Popen together with os.fork to accomplish the same thing. Instead of using close_fds it just closes the pipes at the right places. Much simpler than trying to use select.select, and takes full advantage of system pipe buffers.

    from subprocess import Popen, PIPE
    import os
    import sys
    
    p1 = Popen(["cat"], stdin=PIPE, stdout=PIPE)
    
    pid = os.fork()
    
    if pid: #parent
        p1.stdin.close()
        p2 = Popen(["cat"], stdin=p1.stdout, stdout=PIPE)
        data = p2.stdout.read()
        sys.stdout.write(data)
        p2.stdout.close()
    
    else: #child
        data_to_write = 'hello world\n' * 100000
        p1.stdin.write(data_to_write)
        p1.stdin.close()
    

提交回复
热议问题