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?
To take input (or arguments) from the command line, the simplest way is to use another one of Python's default modules: sys. Specifically, you're interested in sys. argv, a list of words (separated by space) that's entered at the same time that you launch the script.
To access command-line arguments from within a Python program, first import the sys package. You can then refer to the full set of command-line arguments, including the function name itself, by referring to a list named argv. In either case, argv refers to a list of command-line arguments, all stored as strings.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With