This question already has answers here:
Closed 5 years ago.
Python command line input in a process
(2个答案)
我的应用程序需要一个进程中的input()。我写了一个小测试,因为我遇到了一些问题。
from multiprocessing import Process, Queue

class InputCatcher(Process):
    def __init__(self, input_queue):
        Process.__init__(self)
        self.input_queue = input_queue

    def run(self):
        while True:
            self.input_queue.put(input())


input_queue = Queue()
ic = InputCatcher(input_queue)
ic.daemon = True
ic.start()

while True:
    if not input_queue.empty():
        print(input_queue.get())

不幸的是,我得到了这个错误:
Process InputCatcher-1:
Traceback (most recent call last):
File "/usr/lib/python3.3/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/****/PycharmProjects/****/test/inputtestproces.py", line 13, in run
self.input_queue.put(input())
EOFError: EOF when reading a line

有办法让它工作吗?

最佳答案

multiprocessing文档(https://docs.python.org/2/library/multiprocessing.html#all-platforms):
最初无条件调用的多处理:
os.close(sys.stdin.fileno())
multiprocessing.Process._bootstrap()方法中-这导致了问题
过程中的过程。已更改为:
sys.stdin.close()
sys.stdin = open(os.devnull)
因此,分叉进程将关闭该进程的stdin,并用/dev/null的文件描述符替换它。
在回答您的问题时,解决这个问题的方法是反转代码的逻辑,让主进程等待用户输入,而分叉进程执行主进程的原始工作。
顺便说一下:从您发布的代码来看,使用threading模块可能比使用multiprocessing模块更好。除非您计划在分叉进程中执行一些计算密集型的工作,否则multiprocessing模块有点像过度杀戮。此外,线程间通信通常比进程间通信简单。

关于python - input()在进程内部不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23083466/

10-14 15:47
查看更多