你不能像那样使用p.stdout;如果您要求“整个标准输出”,则只有在过程终止(或管道缓冲器填充,这可能需要很长时间)时才可用.
您需要逐行读取进程的stdout.
while True:
ln = p.stdout.readline()
if '' == ln:
break
m = re.search("Thread (?P\d+)", ln);
if m:
# use m.group() to extract information
# e.g. m.group('id') will hold the 12345 from "Thread 12345"
最好将stdout设置为行缓冲(通常尽可能完全缓冲),但我认为这只能在被调用程序中完成.
我们在这里要考虑两个缓冲区.一个是C程序的输出缓冲区.这可能是不存在的(无缓冲输出),线路缓冲或完全缓冲(1K,4K或8K是一些可能的大小).
在程序中,调用“printf()”.输出结果如下:
> out,如果没有缓冲
>进入缓冲区;如果行缓冲,则输出缓冲区中所有换行终止的行;
>进入缓冲区;然后输出第一个4K,如果用4K缓冲器完全缓冲并且缓冲区比4K更饱满.
现在输出进入Python的管道.这也可以是完全缓冲(stdout)或行缓冲(readline).所以输出结果如下:
>对python程序的逻辑,如果管道中有一个完整的换行终止行,我们正在使用readline
>到缓冲区,如果管道中的数量少于4K,我们在stdout中使用“for ln”.
在最后一种情况下,缓冲区将以4K块的形式进入Python逻辑.
现在让我们想象一个行缓冲的C程序向Python程序输出一行,每行1K个字符(如果C程序完全缓冲,那么可以做的就不多了!)
在循环中读取stdout,我们会看到(在for循环中):
> t = 0 ……没什么
> t = 1 …没有(缓冲区已满50%)
> t = 2 …没有(缓冲区已满75%)
> t = 3 …四行输出
> t = 4 ……没什么
…
通过readline阅读我们会得到:
> t = 0 ……一行
> t = 1 …一行
> t = 2 ……一行
> t = 3 ……一行
例
在这里,我运行“ping -c 3 -i 2 127.0.0.1”,以便以两秒的间隔将三个数据包发送到localhost.一次ping操作大约需要6秒钟.我从ping读取输出,并打印时间戳. ping的整个输出足够小,以至于它适合Python的全缓冲区.
#!/usr/bin/python
import subprocess
from time import gmtime, strftime
p = subprocess.Popen(["ping", "-c", "3", "-i", "2", "127.0.0.1"],
stdout=subprocess.PIPE)
for ln in p.stdout:
print strftime("%H:%M:%S", gmtime()) + " received " + ln
# Now I start the same process again, reading the input the other way.
p = subprocess.Popen(["ping", "-c", "3", "-i", "2", "127.0.0.1"],
stdout=subprocess.PIPE)
while True:
ln = p.stdout.readline()
if '' == ln:
break
print strftime("%H:%M:%S", gmtime()) + " received " + ln
我在Linux机器上收到的输出正如预期的那样:
(nothing for the first six seconds)
15:40:10 received PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
15:40:10 received 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.037 ms
15:40:10 received 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.034 ms
15:40:10 received 64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.031 ms
15:40:10 received
15:40:10 received --- 127.0.0.1 ping statistics ---
15:40:10 received 3 packets transmitted, 3 received, 0% packet loss, time 3998ms
15:40:10 received rtt min/avg/max/mdev = 0.031/0.034/0.037/0.002 ms
15:40:10 received PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
15:40:10 received 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.041 ms
15:40:12 received 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.039 ms
15:40:14 received 64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.035 ms
15:40:14 received
15:40:14 received --- 127.0.0.1 ping statistics ---
15:40:14 received 3 packets transmitted, 3 received, 0% packet loss, time 3999ms
15:40:14 received rtt min/avg/max/mdev = 0.035/0.038/0.041/0.005 ms