pipe large amount of data to stdin while using subprocess.Popen

后端 未结 10 638
花落未央
花落未央 2020-12-08 11:08

I\'m kind of struggling to understand what is the python way of solving this simple problem.

My problem is quite simple. If you use the follwing code it will hang. T

10条回答
  •  悲哀的现实
    2020-12-08 11:50

    If you don't want to keep all the data in memory, you have to use select. E.g. something like:

    import subprocess
    from select import select
    import os
    
    proc = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    
    i = 0;
    while True:
        rlist, wlist, xlist = [proc.stdout], [], []
        if i < 100000:
            wlist.append(proc.stdin)
        rlist, wlist, xlist = select(rlist, wlist, xlist)
        if proc.stdout in rlist:
            out = os.read(proc.stdout.fileno(), 10)
            print out,
            if not out:
                break
        if proc.stdin in wlist:
            proc.stdin.write('%d\n' % i)
            i += 1
            if i >= 100000:
                proc.stdin.close()
    

提交回复
热议问题