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

后端 未结 10 616
花落未央
花落未央 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:56

    The simplest solution I can think of:

    from subprocess import Popen, PIPE
    from threading import Thread
    
    s = map(str,xrange(10000)) # a large string
    p = Popen(['cat'], stdin=PIPE, stdout=PIPE, bufsize=1)
    Thread(target=lambda: any((p.stdin.write(b) for b in s)) or p.stdin.close()).start()
    print (p.stdout.read())
    

    Buffered version:

    from subprocess import Popen, PIPE
    from threading import Thread
    
    s = map(str,xrange(10000)) # a large string
    n = 1024 # buffer size
    p = Popen(['cat'], stdin=PIPE, stdout=PIPE, bufsize=n)
    Thread(target=lambda: any((p.stdin.write(c) for c in (s[i:i+n] for i in xrange(0, len(s), n)))) or p.stdin.close()).start()
    print (p.stdout.read())
    

提交回复
热议问题