带python子进程替换的grep

2024-09-26 17:40:38 发布

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

在交换机上,我运行ntpq -nc rv并得到一个输出:

associd=0 status=0715 leap_none, sync_ntp, 1 event, clock_sync, version="ntpd 4.2.6p3-RC10@1.2239-o Mon Mar 21 02:53:48 UTC 2016 (1)", processor="x86_64", system="Linux/3.4.43.Ar-3052562.4155M", leap=00, stratum=2, precision=-21, rootdelay=23.062, rootdisp=46.473, refid=17.253.24.125, reftime=dbf98d39.76cf93ad Mon, Dec 12 2016 20:55:21.464, clock=dbf9943.026ea63c Mon, Dec 12 2016 21:28:03.009, peer=43497, tc=10, mintc=3, offset=-0.114, frequency=27.326, sys_jitter=0.151, clk_jitter=0.162, clk_wander=0.028

我试图使用Python的subprocess模块创建bashshell命令,以便仅提取上面示例中的“offset”或-0.114的值

我注意到我可以使用subprocess replacement mod或sh来实现这一点:

import sh

print(sh.grep(sh.ntpq("-nc rv"), 'offset'))

我得到:

mintc=3, offset=-0.114, frequency=27.326, sys_jitter=0.151,

这是不正确的,因为我只需要'offset'的值-0.114。你知道吗

不知道我在这里做错了什么,是我的grep函数还是我没有正确使用sh模块。你知道吗


Tags: shsyssyncleapdecoffsetncfrequency
1条回答
网友
1楼 · 发布于 2024-09-26 17:40:38

grep逐行读取;它返回与输入的任何部分匹配的每一行。但我认为grep太过分了。一旦获得shell输出,只需搜索output之后的内容:

items = sh.ntpq("-nc rv").split(',')
for pair in items:
    name, value = pair.split('=')
    # strip because we weren't careful with whitespace
    if name.strip() == 'offset':
        print(value.strip())

相关问题 更多 >

    热门问题