我想在 Python 中生成一个子进程,它的标准流用于其他目的,我不能碰它们,我想有一个独立于标准流的专用管道用于我自己的目的。
在 Python 版本 2 中,以下工作:
foobar.py:
#!/usr/bin/python
from os import pipe, environ, read
import subprocess
output, input = pipe()
new_environ = environ.copy()
new_environ["PIPE_INPUT"] = str(input)
subprocess.Popen(['./a.out'], env=new_environ)
print(read(output, 6))
和a.out是从foobar.c编译而来的:
#include <unistd.h>
#include <stdlib.h>
void main() {
write(atoi(getenv("PIPE_INPUT")), "foobar", 6);
}
这有效,./foobar.py 打印 foobar。
但是,使用 shebang 行
#!/usr/bin/python3
它不起作用。当然,这是因为,根据文档,在 Python 3 中,描述符是不可继承的。
好吧,那么我如何在 Python 3 中执行此操作,并且同样的代码也适用于 Python 2。我不能为不同的 Python 使用不同的代码,必须是 Python 2 和 3 的可移植代码。
请您参考如下方法:
如有必要,要使 input 描述符可继承,请使用
import os
try:
os.set_inheritable(input, True)
except AttributeError:
# This is Python 3.3 or older -> Nothing to do
pass
然后必须将 Popen 调用修改为
subprocess.Popen(['./a.out'], env=new_environ, close_fds=False)
适用于 Python 2 和 Python 3。
