子进程中的Python用户输入 [英] Python user input in child process
问题描述
我正在尝试创建一个子进程,该进程可以通过raw_input()或input()接受输入,但是在请求输入时出现了线性错误 EOFError:EOF .
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.
我这样做是为了在python中进行多处理实验,并且我还记得这很容易在C中工作.是否有一种解决方法,而不使用从主进程到其子进程的管道或队列?我真的希望孩子处理用户输入的内容.
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.
推荐答案
我修改了您的示例,它似乎可以工作:
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()
这篇关于子进程中的Python用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!