grep与python子进程替换

grep与python子进程替换,python,subprocess,sh,Python,Subprocess,Sh,在一个开关上,我运行ntpq-nc rv,得到一个输出: associd=0状态=0715跳跃无,同步ntp,1事件,时钟同步, version=“ntpd 4.2.6p3-RC10@1.2239-o 2016年3月21日星期一02:53:48 UTC(1)”, processor=“x86_64”,system=“Linux/3.4.43.Ar-3052562.4155M”,leap=00, 地层=2,精度=21,根延迟=23.062,根显示=46.473, refid=17.253.24.1

在一个开关上,我运行
ntpq-nc rv
,得到一个输出:

associd=0状态=0715跳跃无,同步ntp,1事件,时钟同步, version=“ntpd 4.2.6p3-RC10@1.2239-o 2016年3月21日星期一02:53:48 UTC(1)”, processor=“x86_64”,system=“Linux/3.4.43.Ar-3052562.4155M”,leap=00, 地层=2,精度=21,根延迟=23.062,根显示=46.473, refid=17.253.24.125, 参考时间=dbf98d39.76cf93ad 2016年12月12日星期一20:55:21.464, clock=dbf9943.026ea63c 2016年12月12日星期一21:28:03.009,peer=43497, tc=10,mintc=3,偏移量=-0.114,频率=27.326,系统抖动=0.151, 时钟抖动=0.162,时钟漂移=0.028

我试图使用Python的子流程模块创建一个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模块

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

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())

你可以考虑用Python来标记它,因为它与shell或GRIP无关。