这段代码是想在获取子进程里面的实时的标准输出结果,而不是等子进程结束以后再输出最后的结果,但是每次执行输出的结果都不一样,比较费解,求大神指点?感谢!运行环境ubuntu 12.04.3 64bit
#!/usr/bin/python
import subprocess
def run_cmd_redis(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
res = p.returncode
while res is None:
line = p.stdout.readline()
res = p.poll()
print p.returncode
print line
run_cmd_redis('ifconfig')
root
@demo1 :~/# ./test.py
None
eth0 Link encap:Ethernet HWaddr 00:0c:29:28:b5:d3
None
inet addr:10.1.35.226 Bcast:10.1.35.255 Mask:255.255.255.0
None
inet6 addr: fe80::20c:29ff:fe28:b5d3/64 Scope:Link
None
UP BROADCAST MULTICAST MTU:1500 Metric:1
None
RX packets:92 errors:0 dropped:10 overruns:0 frame:0
None
TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
None
collisions:0 txqueuelen:1000
None
RX bytes:6274 (6.2 KB) TX bytes:468 (468.0 B)
0
root
@demo1 :~/# ./test.py
None
eth0 Link encap:Ethernet HWaddr 00:0c:29:28:b5:d3
0
inet addr:10.1.35.226 Bcast:10.1.35.255 Mask:255.255.255.0
root
@demo1 :~/# ./test.py
None
eth0 Link encap:Ethernet HWaddr 00:0c:29:28:b5:d3
0
inet addr:10.1.35.226 Bcast:10.1.35.255 Mask:255.255.255.0
root
@demo1 :~/# ./test.py
None
eth0 Link encap:Ethernet HWaddr 00:0c:29:28:b5:d3
None
inet addr:10.1.35.226 Bcast:10.1.35.255 Mask:255.255.255.0
None
inet6 addr: fe80::20c:29ff:fe28:b5d3/64 Scope:Link
None
UP BROADCAST MULTICAST MTU:1500 Metric:1
None
RX packets:92 errors:0 dropped:10 overruns:0 frame:0
None
TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
None
collisions:0 txqueuelen:1000
None
RX bytes:6274 (6.2 KB) TX bytes:468 (468.0 B)
None
None
eth1 Link encap:Ethernet HWaddr 00:0c:29:28:b5:dd
None
inet addr:10.1.9.226 Bcast:10.1.9.255 Mask:255.255.255.0
None
inet6 addr: fe80::20c:29ff:fe28:b5dd/64 Scope:Link
None
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
None
RX packets:27569982 errors:0 dropped:1038 overruns:0 frame:0
None
TX packets:27813981 errors:0 dropped:0 overruns:0 carrier:0
None
collisions:0 txqueuelen:1000
None
RX bytes:2791401044 (2.7 GB) TX bytes:5211953339 (5.2 GB)
None
None
lo Link encap:Local Loopback
None
inet addr:127.0.0.1 Mask:255.0.0.0
None
inet6 addr: ::1/128 Scope:Host
None
UP LOOPBACK RUNNING MTU:65536 Metric:1
None
RX packets:17800715 errors:0 dropped:0 overruns:0 frame:0
None
TX packets:17800715 errors:0 dropped:0 overruns:0 carrier:0
None
collisions:0 txqueuelen:0
None
RX bytes:1538890210 (1.5 GB) TX bytes:1538890210 (1.5 GB)
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
0