我是linux环境的新手,但是由于我的新项目,我正在学习并且我喜欢它(来自vxwork时代)。现在我的问题是如何使用 bash 脚本从命令“i2cdetect”中过滤 I2c 地址。我听说我可以使用 SED 或 AWKD 来扫描和搜索文本。 所以基本上我想获取每个 i2c 地址,例如 0c、5b、5c、UU、6e、6f。
感谢您提供的任何线索或帮助。
root@plnx_aarch64:/# i2cDetect -y -r 3 0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- -- -- -- 0c -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- 5b 5c -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 6e 6f
70:UU -- -- -- -- -- -- --
我写了一个函数来做到这一点。我不确定是否有更好的方法,但这似乎确实有效。
import re
def get_addresses(i2cdetect_output):
''' Takes output from i2cdetect and extracts the addresses
for the entries.
'''
# Get the rows, minus the first one
i2cdetect_rows = i2cdetect_output.split('\r\n')[1:]
i2cdetect_matrix = []
# Add the rows to the matrix without the numbers and colon at the beginning
for row in i2cdetect_rows:
i2cdetect_matrix.append(filter(None, re.split(' +', row))[1:])
# Add spaces to the first and last rows to make regularly shaped matrix
i2cdetect_matrix[0] = [' ', ' ', ' '] + i2cdetect_matrix[0]
i2cdetect_matrix[7] = i2cdetect_matrix[7][:-1] + [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
# Make a list of the addresses present
address_list = []
for i in range(len(i2cdetect_matrix)):
for j in range(len(i2cdetect_matrix[i])):
if i2cdetect_matrix[i][j] not in (' ', '--', 'UU'):
address_list.append(str(i) + str(format(j, 'x')))
if i2cdetect_matrix[i][j] == 'UU':
address_list.append('UU')
return address_list
i2cdetect_hex_regex = re.compile(r'[0-9A-Fa-f]{2} ')
@staticmethod
def i2c_address_list() -> list:
from subprocess import PIPE, Popen
process = Popen(args=['/usr/sbin/i2cdetect', '-y', '1'], stdout=PIPE)
stdout, _ = process.communicate()
process.terminate()
stdout = stdout.decode('ascii')
address_list = I2C.i2cdetect_hex_regex.findall(stdout)
address_list = [int(x.strip(), base=16) for x in address_list]
return address_list
试穿这款尺码!它还展示了如何运行 i2c 检测命令(假设您不需要 sudo;这适用于我的情况)。正如您所看到的,i2cDetect 输出中的十六进制是唯一的“HH”形式(注意空格字符)。列上的那些有一个“:”而不是空格,所以它不应该选择这些。