Python subprocess Popen 仅将 stdout 输出到变量

2 投票
1 回答
3964 浏览
提问于 2025-04-27 21:45

我想做一些简单的事情,但我不太明白……我在谷歌上搜索了很多,但没找到合适的答案!

我正在做这个:

from subprocess import Popen, PIPE

p1 = Popen(["fping", '-C10', '-B1', '-p500',
'-r1', '-s', '172.29.172.106'], stdout=PIPE)
output = p1.communicate()

所以,python执行我的命令,communicate会等待返回的结果,这样是没问题的。但是,我不知道为什么它会显示输出……像这样:

172.29.172.106 : 13.50 18.56 13.22 13.42 13.39 187.62 13.34 13.51 13.36 26.35

       1 targets
       1 alive
       0 unreachable
       0 unknown addresses

       0 timeouts (waiting for response)
      10 ICMP Echos sent
      10 ICMP Echo Replies received
       0 other ICMP received

 13.2 ms (min round trip time)
 32.6 ms (avg round trip time)
 187 ms (max round trip time)
        4.530 sec (elapsed real time)

我只想执行一个命令,然后把输出重定向到一个变量里,但我不想显示输出,因为这会把我的crontab日志文件搞得满满的!

所以我的问题是:怎么用popen(或者其他函数)来执行一个命令,并把输出重定向到一个变量里,而不显示出来呢?

祝好,

暂无标签

1 个回答

2
import subprocess 
p1 = Popen(["fping", '-C10', '-B1', '-p500','-r1', '-s', '172.29.172.106'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output,error = p1.communicate()

试试这个。

撰写回答