【问题标题】:Python user input in child process子进程中的 Python 用户输入
【发布时间】:2012-11-29 21:23:03
【问题描述】:

我正在尝试创建一个可以通过 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()

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

【问题讨论】:

    标签: python-2.7 multiprocessing user-input


    【解决方案1】:

    我的回答取自这里: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()
    

    【讨论】:

    • 这对你有用吗?我得到 ValueError: I/O operation on closed file
    • 是的。也许行为取决于操作系统。你在什么操作系统上?我在 Linux 上。
    • Windows 8,我猜这是问题
    • 这可能无济于事,但值得一试:检查如果将 os.dup() 的返回值作为 newstdin 传递并将 os.fdopen() 移动到 child() 函数会发生什么.
    • 这行得通,但孩子现在无法从 raw_input() 退出,整个脚本奇怪地在 3~4 秒后存在,并且所有打印语句都不起作用。
    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 2018-10-23
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多