Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

multiprocessing - Python command line input in a process

I've got a system that needs to receive input from a few different processes. The simplest is just a command line where the user enters data manually. This data will be added to a multiprocessing.Queue and handled later by the main process, but I'm not even getting that far; calling raw_input inside a process doesn't seem to work. I pulled out the meat of the code and here's an example:

import multiprocessing

def f():
    while True:
        raw_input('>>>')

p = multiprocessing.Process(target = f)
p.start()

This simple code throws this:

~$ python test.py
Process Process-1:
Traceback (most recent call last):
  File "/usr/lib/python2.6/multiprocessing/process.py", line 232, in _bootstrap
    self.run()
  File "/usr/lib/python2.6/multiprocessing/process.py", line 88, in run
    self._target(*self._args, **self._kwargs)
  File "test.py", line 5, in f
    raw_input('>>>')
EOFError: EOF when reading a line
>>>~$

How can I get command line input in a process in Python?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you spawn a thread in Python, it closes stdin. You can't use a subprocess to collect standard input. Use the main thread to collect input instead and post them to the Queue from the main thread. It may be possible to pass the stdin to another thread, but you likely need to close it in your main thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...