这是我使用 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/