子进程中的Python用户输入

时间:2012-12-12 07:58:13

标签: python-2.7 multiprocessing user-input

我正在尝试创建一个可以通过raw_input()或input()获取输入的子进程,但是当我要求输入时,我得到了衬里错误 EOFError:EOF 的结束。

我这样做是为了在python中尝试多处理,我记得这很容易在C中工作。有没有使用管道或队列从主进程到它的孩子的解决方法?我非常希望孩子能够处理用户输入。

def child():
    print 'test' 
    message = raw_input() #this is where this process fails
    print message

def main():
    p =  Process(target = child)
    p.start()
    p.join()

if __name__ == '__main__':
    main()

我写了一些测试代码,希望能够展示我想要实现的目标。

1 个答案:

答案 0 :(得分:2)

我的答案来自这里:Is there any way to pass 'stdin' as an argument to another process in python?

我修改了你的例子,似乎有效:

from multiprocessing.process import Process
import sys
import os

def child(newstdin):
    sys.stdin = newstdin
    print 'test' 
    message = raw_input() #this is where this process doesn't fail anymore
    print message

def main():
    newstdin = os.fdopen(os.dup(sys.stdin.fileno()))
    p =  Process(target = child, args=(newstdin,))
    p.start()
    p.join()

if __name__ == '__main__':
    main()