Python user input in child process

雨燕双飞 提交于 2019-12-02 05:40:51

问题


I'm trying to create a child process that can take input through raw_input() or input(), but I'm getting an end of liner error EOFError: EOF when asking for input.

I'm doing this to experiment with multiprocessing in python, and I remember this easily working in C. Is there a workaround without using pipes or queues from the main process to it's child ? I'd really like the child to deal with user input.

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()

I wrote some test code that hopefully shows what I'm trying to achieve.


回答1:


My answer is taken from here: Is there any way to pass 'stdin' as an argument to another process in python?

I have modified your example and it seems to work:

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()


来源:https://stackoverflow.com/questions/13835250/python-user-input-in-child-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!