我正在研究树莓派,想用Python从/proc/cpuinfo
中提取cpuinfo
。这是我要执行的以下命令:
cat /proc/cpuinfo | grep 'model name|Hardware|Serial' | uniq
当我直接在树莓派终端上运行命令时,我得到以下输出:
model name : ARMv7 Processor rev 4 (v7l)
Hardware : BCM2835
Serial : 0000000083a747d7
这也是我所期望的。我想把它放到一个 Python 列表中,所以我使用了subprocess.check_output()
方法并使用了一个.split()
,考虑到它的格式化方式,.splitlines()
。但是使用subprocess.check_output()
调用相同的命令我没有得到我期望的。这是我在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()
。即:
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 返回的值吗?请帮助了解如何解决。
谢谢
比较:
items = dict(s.split('t: ') for s in open('/proc/cpuinfo', 'r').read().splitlines() if s.startswith(('model name', 'Hardware', 'Serial')))
在 Python3 中,subprocess.check_output()
返回需要解码到string
才能使用字符串函数的bytes
。另一种选择是使用旧版subprocess.getoutput()
功能。
以下代码为我完成了这项工作:
items = [s.split('t: ') for s in subprocess.getoutput(["cat /proc/cpuinfo | grep 'model name|Hardware|Serial' | uniq "]).splitlines()]