subprocess 的 Popen用法

使用Popen方法时,需要获取输出内容时可以按如下方法获取:

 1 # -*- coding:utf-8 -*-
 2 
 3 import subprocess
 4 cmd = r"ping www.baidu.com"
 5 result = subprocess.Popen(cmd, stdout=subprocess.PIPE)  # 将输出内容存至缓存中
 6 print(result.stdout.read().decode("gbk"))  # 通过从缓存中读取内容并解码显示
 7 
 8 输出显示如下:
 9 正在 Ping www.wshifen.com [103.235.46.39] 具有 32 字节的数据:
10 来自 103.235.46.39 的回复: 字节=32 时间=334ms TTL=39
11 来自 103.235.46.39 的回复: 字节=32 时间=340ms TTL=39
12 来自 103.235.46.39 的回复: 字节=32 时间=317ms TTL=39
13 来自 103.235.46.39 的回复: 字节=32 时间=342ms TTL=39
14 
15 103.235.46.39 的 Ping 统计信息:
16     数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
17 往返行程的估计时间(以毫秒为单位):
18     最短 = 317ms,最长 = 342ms,平均 = 333ms
19 
20 
21 Process finished with exit code 0

获取Popen的输出时,可以通过 stdout从缓存中读出来,那怎么写到缓存中呢,只需要在Popen方法的参数中带上stdout=subprocess.PIPE这个关键字参数即会写入到缓存中,当然了,这个里面还有一个参数stdin这个关键字参数,这个参数可以接收到从其它管道中的输出做为这次的输入,例如:

1  import subprocess
2 child1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)
3 child2 = subprocess.Popen(["grep","0:0"],stdin=child1.stdout, stdout=subprocess.PIPE)
4 out = child2.communicate()
原文地址:https://www.cnblogs.com/aziji/p/12029382.html