【发布时间】:2017-05-03 16:47:48
【问题描述】:
我有这个 shell 命令,我想在 python 中得到它的字符串输出。
ip link show | egrep -o '([-_.[:alnum:]]+-eth[[:digit:]]+)'
会输出:
s1-eth1
s3-eth1
s4-eth2
...
使用os.system 返回整数错误值。
我试过了:
from subprocess import Popen, PIPE
import shlex
cmd1 = shlex.split('ip link show')
cmd2 = shlex.split("egrep -o '([-_.[:alnum:]]+-eth[[:digit:]]+)'")
proc1 = Popen(cmd1,stdout=PIPE)
proc2 = Popen(cmd2,stdin=proc1.stdout,stdout=PIPE,stderr=PIPE)
proc1.stdout.close()
out,err=proc2.communicate()
print('out: {0}'.format(out))
print('err: {0}'.format(err))
输出grep使用帮助
ip link show 会输出:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eno16777736: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT group default qlen 1000
link/ether 00:0c:29:b3:aa:25 brd ff:ff:ff:ff:ff:ff
3: ovs-system: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default
link/ether d2:c1:69:6f:ba:0d brd ff:ff:ff:ff:ff:ff
912: s2-eth3@s1-eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc htb master ovs-system state UP mode DEFAULT group default qlen 1000
link/ether de:3e:e2:5a:56:b3 brd ff:ff:ff:ff:ff:ff
913: s1-eth1@s2-eth3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc htb master ovs-system state UP mode DEFAULT group default qlen 1000
link/ether 1e:67:0b:14:7d:c9 brd ff:ff:ff:ff:ff:ff
914: s3-eth3@s1-eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc htb master ovs-system state UP mode DEFAULT group default qlen 1000
link/ether da:05:df:f2:02:66 brd ff:ff:ff:ff:ff:ff
915: s1-eth2@s3-eth3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc htb master ovs-system state UP mode DEFAULT group default qlen 1000
link/ether de:cc:94:85:81:22 brd ff:ff:ff:ff:ff:ff
...
我想从中获取这些值: s2-eth3 s1-eth1 ...
【问题讨论】:
标签: python string shell command output