场景:在Python中使用multiprocessing模块的Process创建子进程,试图在子进程中获取键盘输入。

使用input()

在子进程中使用input()会弹出报错信息:EOFError: EOF when reading a line。

代码示例

from multiprocessing import Process
import sys

def test_input():
    info = input()
    print("start print info!")
    print(info)


if __name__ == "__main__":
    print("start progress!")
    Process(target=test_input).start()

结果输出

start progress!
Process Process-1:
Traceback (most recent call last):
  File "D:\software\Python\lib\multiprocessing\process.py", line 258, in _bootstrap
    self.run()
  File "D:\software\Python\lib\multiprocessing\process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "D:\text_project\python\验收2\test.py", line 5, in test_input
    info = input()
EOFError: EOF when reading a line

Process finished with exit code 0

使用sys.stdin.readline()

在子进程中使用sys.stdin.readline(),发现并不会等待键盘输入。

代码示例

import sys
from multiprocessing import Process


def test_input():
    info = sys.stdin.readline()
    print("start print info!")
    print(info)


if __name__ == "__main__":
    print("start progress!")
    Process(target=test_input).start()

结果输出

start progress!
start print info!


Process finished with exit code 0

使用fn=sys.stdin.fileno()

在主进程中敲写代码fn=sys.stdin.fileno(),然后将获取到的文件描述符fn传入子进程,子进程敲写代码sys.stdin = os.fdopen(fn),然后就可以正常使用sys.stdin.readline()获取键盘输入了。

代码示例

import os
import sys
from multiprocessing import Process


def test_input(fn):
    sys.stdin = os.fdopen(fn)
    info = sys.stdin.readline()
    print("start print info!")
    print(info)


if __name__ == "__main__":
    print("start progress!")
    fn = sys.stdin.fileno()
    Process(target=test_input, args=(fn, )).start()

结果输出

start progress!
this is my input.
start print info!
this is my input.


Process finished with exit code 0