将多个属性分配给 Subprocess.Popen 的 STDOUT

Assigning multiple attributes to Subprocess.Popen's STDOUT

我正在制作一个多 ping 软件。为此,我使用 subprocess.Popen 来 ping 设备。我不想显示正常输出,所以我使用 STDOUT = DEVNULL 来隐藏文本。现在我需要将文本添加到一些日志文件中供用户检查,但我也不希望在终端中显示文本。我有什么办法可以为 STDOUT 分配两个值 - 例如。 stdout = (DEVNULL, PIPE) 或者是否有任何其他值可以完成我需要的任务?

基本上是这样的:

pop = subprocess.Popen([Some Command], shell = True, stdout = (subprocess.DEVNULL, subprocess.PIPE))
res = pop.communicate()

设置stdout=PIPE不会写入终端,所以不需要使用DEVNULL来禁止输出。问题是,对于 PIPE,您首先必须将输出读入 res,然后将 res 写入日志文件。

您可以直接将打开的文件作为 stdout 传递给 Popen:

with open('logfile', 'w') as f:
    proc = subprocess.Popen(["/bin/ls"], stdout=f)
    proc.wait()
with open('logfile', 'r') as f:
    print(f.read())