且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 多处理标准输入

更新时间:2023-11-17 23:26:46

当你看一下 Python 的实现 multiprocessing.Process._bootstrap() 你会看到这个:

When you take a look at Pythons implementation of multiprocessing.Process._bootstrap() you will see this:

if sys.stdin is not None:
    try:
        sys.stdin.close()
        sys.stdin = open(os.devnull)
    except (OSError, ValueError):
        pass

您也可以通过以下方式确认:

You can also confirm this by using:

>>> import sys
>>> import multiprocessing
>>> def func():
...     print(sys.stdin)
... 
>>> p = multiprocessing.Process(target=func)
>>> p.start()
>>> <_io.TextIOWrapper name='/dev/null' mode='r' encoding='UTF-8'>

并且从 os.devnull 读取立即返回空结果:

And reading from os.devnull immediately returns empty result:

>>> import os
>>> f = open(os.devnull)
>>> f.read(1)
''

您可以使用 open(0)代码>:

You can work this around by using open(0):

file 是一个字符串或字节对象,给出要打开的文件的路径名(绝对或相对于当前工作目录)或要打开的文件的 整数文件描述符包裹.(如果给定文件描述符,则在关闭返回的 I/O 对象时关闭,除非 closefd 设置为 False.)

file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)

还有 "0 文件描述符":

文件描述符是与当前进程打开的文件相对应的小整数.比如标准输入通常是文件描述符0,标准输出是1,标准错误是2:

File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2:

>>> def func():
...     sys.stdin = open(0)
...     print(sys.stdin)
...     c = sys.stdin.read(1)
...     print('Got', c)
... 
>>> multiprocessing.Process(target=func).start()
>>> <_io.TextIOWrapper name=0 mode='r' encoding='UTF-8'>
Got a