从Python中的管道捕获的标准输出被截断 [英] Stdout captured from pipe in Python is truncated

查看:214
本文介绍了从Python中的管道捕获的标准输出被截断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to capture the ouput of dpkg --list | grep linux-image in Python 2.6.5 on Ubuntu 10.04.

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]

stdout的内容是:

The content of stdout is:


>>> 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不同:

However, this is not the same as running dpkg --list | grep linux-image in a shell:


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的输出被截断了:

Looking at the first line, one can see that the output in Python is truncated:

rc  linux-image-2. 2.6.31-14.48

代替

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

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

Why does it do that and is there a way to get exactly the same output in Python?

推荐答案

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环境变量的值. 在subprocess.Popen中设置LANG=C将使dpkg的输出更像您在终端上看到的那样.

The dpkg command's output depends on the value of the LANG environment variable. Setting LANG=C in subprocess.Popen will make dpkg's output more like what you see from the terminal.

这篇关于从Python中的管道捕获的标准输出被截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆