简体   繁体   English

进程中的python命令行输入

[英]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;这些数据将被添加到multiprocessing.Queue并稍后由主进程处理,但我什至没有走那么远; calling raw_input inside a process doesn't seem to work.在进程内调用raw_input似乎不起作用。 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?如何在 Python 的进程中获取命令行输入?

When you spawn a thread in Python, it closes stdin .当您在 Python 中生成一个线程时,它会关闭 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.可以将 stdin 传递给另一个线程,但您可能需要在主线程中关闭它。

I was able to work around this by using fdopen() to reopen stdin in the subprocess.我能够通过使用 fdopen() 在子进程中重新打开 stdin 来解决这个问题。 See this answer .看到这个答案 It seems to be working, I don't know if there are any hidden risks.好像可以用,不知道有没有什么隐患。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM