子进程中的 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.
推荐答案
我的答案取自这里:有没有办法将'stdin'作为参数传递给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()
这篇关于子进程中的 Python 用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!