首页 > 解决方案 > 在 Popen 中将标准输出(或标准输入)设置为 subprocess.PIPE 究竟意味着什么?

问题描述

我已经阅读有关python 中子进程的文档,但仍然不能完全理解这一点。

使用 Popen 时,我们将参数stdout(或stdin)设置为subprocesses.PIPE,这实际上是什么意思?

文件说

stdin、stdout 和 stderr 分别指定了执行程序的标准输入、标准输出和标准错误文件句柄... PIPE 表示应该创建一个通往子进程的新管道。

这是什么意思?

例如,如果我有两个子流程都带有标准输出到 PIPE,输出是否混合?(我不这么认为)

更重要的是,如果我有一个 stdout 设置为 PIPE 的子进程,然后是另一个 stdin 设置为 PIPE 的子进程,那么该管道是否相同,一个输出到另一个?

有人可以向我解释一下对我来说似乎很重要的那部分文档吗?


附加说明:例如

import os
import signal
import subprocess
import time

# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before  exec() to run the shell.
pro = subprocess.Popen("sar -u 1 > mylog.log", stdout=subprocess.PIPE, 
                       shell=True, preexec_fn=os.setsid) 

// Here another subprocess
subprocess.Popen(some_command, stdin=subprocess.PIPE)
time.sleep(10)

os.killpg(os.getpgid(pro.pid), signal.SIGTERM) 

sar 的输出是否作为“某些命令”的输入?

标签: pythonsubprocesspipe

解决方案


请参阅文档

如您所见,thePIPE是一个特殊值,它“表示应该创建一个到子节点的新管道”。这意味着,stdout=subprocess.PIPEstderr=subprocess.PIPE导致两个不同的管道。

对于您的示例,答案是否定的。这是两种不同的管道。

实际上你可以打印出subprocess.PIPE

print(subprocess.PIPE)
# -1
print(type(subprocess.PIPE))
# int
# So it is just an integer to represent a special case.

推荐阅读