从Python中的管道捕获的stdout被截断

时间:2010-10-03 02:07:25

标签: python subprocess pipe

我想在Ubuntu 10.04上捕获Python 2.6.5中dpkg --list | grep linux-image的输出。

from subprocess import Popen 
from subprocess import PIPE

p1 = Popen(["dpkg", "--list"], stdout=PIPE)
p2 = Popen(["grep", "linux-image"], stdin=p1.stdout, stdout=PIPE)
stdout = p2.communicate()[0]

标准输出的内容是:

>>> print stdout
rc  linux-image-2. 2.6.31-14.48   Linux kernel image for version 2.6.31 on x86
ii  linux-image-2. 2.6.32-22.36   Linux kernel image for version 2.6.32 on x86
ii  linux-image-2. 2.6.32-23.37   Linux kernel image for version 2.6.32 on x86
ii  linux-image-2. 2.6.32-24.43   Linux kernel image for version 2.6.32 on x86
ii  linux-image-2. 2.6.32-25.44   Linux kernel image for version 2.6.32 on x86
ii  linux-image-ge 2.6.32.25.27   Generic Linux kernel image

但是,这与在shell中运行dpkg --list | grep linux-image不同:

cschol@blabla:~$ dpkg --list | grep linux-image
rc  linux-image-2.6.31-14-generic         2.6.31-14.48                                    Linux kernel image for version 2.6.31 on x86
ii  linux-image-2.6.32-22-generic         2.6.32-22.36                                    Linux kernel image for version 2.6.32 on x86
ii  linux-image-2.6.32-23-generic         2.6.32-23.37                                    Linux kernel image for version 2.6.32 on x86
ii  linux-image-2.6.32-24-generic         2.6.32-24.43                                    Linux kernel image for version 2.6.32 on x86
ii  linux-image-2.6.32-25-generic         2.6.32-25.44                                    Linux kernel image for version 2.6.32 on x86
ii  linux-image-generic                   2.6.32.25.27                                    Generic Linux kernel image

查看第一行,可以看到Python中的输出被截断:

rc  linux-image-2. 2.6.31-14.48

而不是

rc  linux-image-2.6.31-14-generic         2.6.31-14.48

为什么会这样做?有没有办法在Python中获得完全相同的输出?

2 个答案:

答案 0 :(得分:4)

import subprocess
p1 = subprocess.Popen(["dpkg", "--list"], stdout=subprocess.PIPE, env={'LANG':'C'})
p2 = subprocess.Popen(["grep", "linux-image"], stdin=p1.stdout, stdout=subprocess.PIPE)
out,err=p2.communicate()
print(out)

dpkg命令的输出取决于LANG环境变量的值。 在LANG=C中设置subprocess.Popen会使dpkg的输出更像您从终端看到的内容。

答案 1 :(得分:4)

无需使用grep!

import subprocess
p1 = subprocess.Popen(["dpkg", "--list"], stdout=subprocess.PIPE, env={'LANG':'C'})
out,err=p1.communicate()
for o in  out.split("\n"):
    if "linux-image" in o:
        print o