python subprocess.check_output 在 cat | 时不返回grep组合

标签 python linux python-3.x raspberry-pi raspberry-pi3

<分区>

我正在使用 raspberry pi 并希望使用 Python 从 /proc/cpuinfo 中提取 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() 方法并使用了 .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')))

关于python subprocess.check_output 在 cat | 时不返回grep组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50334443/

相关文章:

linux - Ubuntu 16.04 上的 Amazon CLI bash 脚本,if 语句上的 "unexpected operator"(语法看起来正确)

python - 你如何将一个列表(无限长)随机分成 3 个子组?

Python 约定为自动化目的强制变量前缀

linux - 如何仅grep包含x和y的内容?

python-3.x - 运行 flask 应用程序时遇到问题

python - matplotlib 和子图属性

python - 如何替换模板文件中变量名的一部分

python - 如何反省 win32com 包装器?

python - 扭曲的进程执行问题

linux - 将 SpecFlow 测试添加到 VSCode 中的 .NET Core 项目