首页 > 解决方案 > python subprocess.check_output 在 cat | 时不返回 grep 组合

问题描述

我正在研究树莓派,并想使用 Python进行cpuinfo提取。/proc/cpuinfo这是我要执行的以下命令:

cat /proc/cpuinfo  | grep 'model name\|Hardware\|Serial' | uniq

当我直接在 Raspberry pi 终端上运行命令时,我得到以下输出:

model name      : ARMv7 Processor rev 4 (v7l)
Hardware        : BCM2835
Serial          : 0000000083a747d7

这也是我所期望的。我想把它放到一个 Python 列表中,所以我使用了该subprocess.check_output()方法并使用了 a.split().splitlines()考虑了它的格式化方式。但是使用subprocess.check_output()I 调用相同的命令并没有得到我期望的结果。这是我在 Python 中运行的代码:

import subprocess
items = [s.split('\t: ') for s in subprocess.check_output(["cat /proc/cpuinfo  | grep 'model name\|Hardware\|Serial' | uniq "], shell=True).splitlines()]

我收到的错误如下:

TypeError: a bytes-like object is required, not 'str'

尝试调试问题:1)在.splitlines()最后删除。IE:

items = [s.split('\t: ') for s in subprocess.check_output(["cat /proc/cpuinfo  | grep 'model name\|Hardware\|Serial' | uniq "], shell=True)

现在输出错误是:

AttributeError: 'int' object has no attribute 'split'

2)关于删除.split

items = [s for s in subprocess.check_output(["cat /proc/cpuinfo  | grep 'model name\|Hardware\|Serial' | uniq "], shell=True)

输出items现在包含以下内容:

>>> items

[109、111、100、101、108、32、110、97、109、101、9、58、32、65、82、77、118、55、32、80、114、111、99、101、115 , 115, 111, 114, 32, 114, 101, 118, 32, 52, 32, 40, 118, 55, 108, 41, 10, 72, 97, 114, 100, 119, 97, 114, 101, 9 , 58, 32, 66, 67, 77, 50, 56, 51, 53, 10, 83, 101, 114, 105, 97, 108, 9, 9, 58, 32, 48, 48, 48, 48, 48 , 48, 48, 48, 56, 51, 97, 55, 52, 55, 100, 55, 10]

几乎似乎grep行为与我预期的不同。但我无法归零到底是什么问题。这些数字是什么?grep 返回的是值吗?请帮忙看看如何解决。

谢谢

标签: pythonlinuxpython-3.xraspberry-piraspberry-pi3

解决方案


在 Python3 中,可以使用需要解码为之前的字符串函数的subprocess.check_output()返回值。另一种选择是使用遗留功能。bytesstringsubprocess.getoutput()

以下代码为我完成了这项工作:

items = [s.split('\t: ') for s in subprocess.getoutput(["cat /proc/cpuinfo  | grep 'model name\|Hardware\|Serial' | uniq "]).splitlines()]

推荐阅读