用Python解析Linux命令

2024-10-03 11:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我使用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)

第3行和第4行显示分配给哪个usb端口的设备序列号。(例如:串行#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

我不知道如何操作输出,以便获得所需的变量。感谢您的帮助。你知道吗


Tags: rundevchildbinusrlocalserialgrep
2条回答

您可以使用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

另一种方法是使用字典在设备序列号和打印机端口之间建立关系:

inString = """/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"""

inString = inString.split("\n")

matches = dict()
serials = dict()

for i in range(len(inString[:2])):
    lp = inString[i][-3:]
    printerPort = int(inString[i].split("-n ")[1][:4])
    matches.update({lp:printerPort})

for i in range(2,len(inString)):
    t = inString[i].split(" ")
    lp = t[3][-3:]
    serial = t[4]
    serials.update({serial:lp})

finalLookup = dict((k,matches[v]) for k,v in serials.items())
print(finalLookup)

输出:

{'SERIAL#1': 5965, 'SERIAL#2': 5964}

然后你可以做:

if not finalLookup['SERIAL#1'] == 5964:
    run some command
else:
    do something else
if not finalLookup['SERIAL#2'] == 5965:
    run some command
else:
    do something else

相关问题 更多 >