python - 使用 Python 解析 Linux 命令

标签 python linux

这是我使用 pexpect 的快速代码片段:

child.expect('tc@')
child.sendline('ps -o args | grep lp_ | grep -v grep | sort -n')
child.expect('tc@')
print(child.before)
child.sendline('exit')

然后输出:

user@myhost:~/Python$ python tctest.py 
tc-hostname:~$ ps -o args | grep lp_ | grep -v grep | sort -n
/usr/local/bin/lp_server -n 5964 -d /dev/usb/lp1
/usr/local/bin/lp_server -n 5965 -d /dev/usb/lp0
{lp_supervisor} /bin/sh /usr/local/lp/lp_supervisor /dev/usb/lp0 SERIAL#1 /var/run/lp/lp_pid/usb_lp0
{lp_supervisor} /bin/sh /usr/local/lp/lp_supervisor /dev/usb/lp1 SERIAL#2 /var/run/lp/lp_pid/usb_lp1

user@myhost:~$

有 4 行输出。前两行显示 usb 设备分配给的打印机端口(例如:第一行显示端口 5964 分配给 lp1)

第三和第四行显示哪个设备序列号分配给哪个USB端口。 (例如:SERIAL#1 分配给 lp0)

我需要以某种方式解析该输出,以便我可以执行以下操作:

If SERIAL#1 is not assigned to 5964:
    run some command
else:
    do something else
If SERIAL#2 is not assigned to 5965:
    run some command
else:
    do something else

我不确定如何操作该输出以便获得所需的变量。感谢您的帮助。

最佳答案

您可以使用 re.findall 从 pexpect 数据中提取端口和串行信息,然后执行类似的操作

import re
data = child.before
ports = re.findall(r'lp_server -n (\d+)', data)
# ['5964', '5965']
serials = re.findall(r'(SERIAL#\d+)', data)
# ['SERIAL#1', 'SERIAL#2']

list(zip(ports, serials))
# [('5964', 'SERIAL#1'), ('5965', 'SERIAL#2')]

for serial, port in zip(ports, serials):
    # Check if serial and port matches expectation

关于python - 使用 Python 解析 Linux 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51173298/

相关文章:

linux - 程序加载后的 RAM 使用情况 - 与 TOP 统计信息不匹配

python - pyparsing nestedExpr 和嵌套括号

python - 路径 'contains_points' 使用贝塞尔曲线产生不正确的结果

python - 如何将 tf.keras 与 bfloat16 结合使用

linux - 虚拟内存到物理内存

ruby - 系统范围的 RVM 安装问题

Python selenium webdriver - 无法一次通过 xpath 单击元素

python - 留一交叉验证

linux - 如何安装 Django 片段转储脚本?

c++ - 要遵循的技巧