Python using STDIN in child Process

后端 未结 4 877
终归单人心
终归单人心 2020-12-11 18:29

So I have a program, in the \"main\" process I fire off a new Process object which (what I want) is to read lines from STDIN and append them to a Queue object.

Ess

4条回答
  •  春和景丽
    2020-12-11 19:20

    If you don't want to pass stdin to the target processes function, like in @Ashelly's answer, or just need to do it for many different processes, you can do it with multiprocessing.Pool via the initializer argument:

    import os, sys, multiprocessing
    
    def square(num=None):
        if not num:
            num = int(raw_input('square what? ')) 
        return num ** 2
    
    def initialize(fd):
        sys.stdin = os.fdopen(fd)
    
    initargs = [sys.stdin.fileno()]
    pool = multiprocessing.Pool(initializer=initialize, initargs=initargs)
    pool.apply(square, [3])
    pool.apply(square)
    

    the above example will print the number 9, followed by a prompt for input and then the square of the input number.

    Just be careful not to have multiple child processes reading from the same descriptor at the same time or things may get... confusing.

提交回复
热议问题