且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Python迭代器提供子进程的标准输入?

更新时间:2023-11-17 23:30:40

简单的方法似乎是从孩子那里分叉并提供输入句柄处理。任何人都可以详细说明这样做的任何可能的缺点吗?或者是否有python模块使其更容易和更安全?

The easy way seems to be to fork and feed the input handle from the child process. Can anyone elaborate on any possible downsides of doing this? Or are there python modules that make it easier and safer?

#!/usr/bin/python
from subprocess import *
import os

def fork_and_input(input, handle):
    """Send input to handle in a child process."""
    # Make sure input is iterable before forking
    input = iter(input)
    if os.fork():
        # Parent
        handle.close()
    else:
        # Child
        try:
            handle.writelines(input)
            handle.close()
        # An IOError here means some *other* part of the program
        # crashed, so don't complain here.
        except IOError:
            pass
        os._exit()

# A really big iterator
input_iterator = ("hello %s\n" % x for x in xrange(100000000))

subproc = Popen("cat", stdin=PIPE, stdout=PIPE)
fork_and_input(input_iterator, subproc.stdin)

for line in subproc.stdout:
    print line,