子进程popen stdout [英] subprocess popen stdout

查看:361
本文介绍了子进程popen stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 subprocess ,但我对此代码有些混淆:

  import subprocess 

proc = subprocess.Popen('lspci',stdout = subprocess.PIPE)
在proc.stdout中的行:
print )

输出:



< b'00:00.0主机桥:英特尔公司至强E3-1200 v2 /第三代核心处理器DRAM控制器(rev 09)\\\
'
b'00:02.0 VGA兼容控制器:Intel公司Xeon E3-1200 v2 /第三代核心处理器显卡控制器(rev 09)\\\
'

正如你所看到的,输出是形成的。但我不知道为什么有字符 b'' \\\
在结尾。



如果我在我的终端运行这个命令,就没有这些char。



正常输出:

  00:00.0主机桥:Intel公司Xeon E3-1200 v2 /第三代核心处理器DRAM控制器(rev 09)
00: 02.0 VGA兼容控制器:Intel公司Xeon E3-1200 v2 /第三代核心处理器显卡控制器(rev 09)

我如何删除它们?

解决方案

你可能使用python3 - python改变了某些对象读/写的方式数据,现在有一个真正的 bytes()对象。要获取所需的字符串,您只需要:

  print(line.decode(utf8))##编码;一个应该打印任何东西,虽然

您可能还需要删除换行符( \ n );我不记得如何 stdout 执行缓冲/报告:

  print(line.decode(utf8)。strip())


I'm learning subprocess, but I have a little confusion with this code:

import subprocess

proc = subprocess.Popen('lspci', stdout=subprocess.PIPE)
for line in proc.stdout:
    print(line)

Output:

b'00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor DRAM Controller (rev 09)\n'
b'00:02.0 VGA compatible controller: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor Graphics Controller (rev 09)\n'

As you can see, the output is formated. But I dont know why there is the character b'' and the \n at the end.

If I run this command in my terminal, there aren't these char.

Normal output:

00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor DRAM Controller (rev 09)
00:02.0 VGA compatible controller: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor Graphics Controller (rev 09)

How could I remove them?

解决方案

You're probably using python3 - python changed up the way certain objects read/write data, and now there's a real bytes() object. To get the string you want, you just need:

print(line.decode("utf8")) ## or some encoding; that one should print anything though

You may also need to strip the newline (\n) from your output; I can't remember how stdout does the buffering/reporting:

print(line.decode("utf8").strip())

这篇关于子进程popen stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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