所以我有一个程序,在“主”进程中我触发了一个新的 Process 对象,它(我想要的)是从 stdin
读取行并将它们附加到 Queue
对象。
本质上,基本系统设置是有一个“命令获取”过程,用户将输入命令/查询,我需要将这些查询发送到在单独进程中运行的其他子系统。我的想法是通过其他系统可以读取的 multiprocessing.Queue
共享这些。
我所拥有的(专注于获取命令/查询)基本上是:
def sub_proc(q):
some_str = ""
while True:
some_str = raw_input("> ")
if some_str.lower() == "quit":
return
q.put_nowait(some_str)
if __name__ == "__main__":
q = Queue()
qproc = Process(target=sub_proc, args=(q,))
qproc.start()
qproc.join()
# now at this point q should contain all the strings entered by the user
问题是我得到:
Process Process-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "/home/blah/blah/blah/blah.py", line 325, in sub_proc
some_str = raw_input("> ")
File "/randompathhere/eclipse/plugins/org.python.pydev_2.1.0.2011052613/PySrc/pydev_sitecustomize/sitecustomize.py", line 181, in raw_input
ret = original_raw_input(prompt)
EOFError: EOF when reading a line
怎么办?
最佳答案
我通过将原始标准输入文件描述符传递给子进程并在那里重新打开它来解决了类似的问题。
def sub_proc(q,fileno):
sys.stdin = os.fdopen(fileno) #open stdin in this process
some_str = ""
while True:
some_str = raw_input("> ")
if some_str.lower() == "quit":
return
q.put_nowait(some_str)
if __name__ == "__main__":
q = Queue()
fn = sys.stdin.fileno() #get original file descriptor
qproc = Process(target=sub_proc, args=(q,fn))
qproc.start()
qproc.join()
这适用于我相对简单的案例。我什至能够在重新打开的流上使用 readline 模块。我不知道它对于更复杂的系统有多稳健。
关于python - 在子进程中使用标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7489967/