python中带变量的awk

2024-10-03 06:22:19 发布

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

假设我在python中有这个命令

response = requests.get('https://host/api/v13/clusters/cluster/services/impalaQueries', verify=false, auth=('user', pass))

其中包含如下示例数据:

 "queryId" : "8f46683f7c2c8fee:6504618f00000000",
"queryState" : "FINISHED",
"rowsProduced" : null,
 etc....

如何在响应变量中使用awk?例如awk-F':''/queryId/


Tags: https命令apihostgetresponseservicerequests
1条回答
网友
1楼 · 发布于 2024-10-03 06:22:19

首先:如果您的数据是JSON(在大多数情况下不是JSON),则不要使用JSON

awk不能准确地解析JSON,这就是像jsawk这样的专用工具被编写为替代工具的全部原因。类似地,Python附带了一个兼容的CSV解析器、多个兼容的XML解析器,以及其他工具,这些工具在处理标准格式方面要比在awk中手工推出的任何工具做得更好。你知道吗

对于您的特定用例,requests模块甚至会在您要求时为您调用Python的JSON解析器:

queryId = requests.get('https://host/api/v13/clusters/cluster/services/impalaQueries',
                       verify=false, auth=('user', pass)).json()['queryId'] 

第二:如果你真的想调用awk,使用subprocess模块
response = '''
ignore this line
queryId foo
ignore this line also
'''

from subprocess import Popen, PIPE
p = Popen(['awk', '-F:', '/queryId/'], stdin=PIPE, stdout=PIPE)
(output, _) = p.communicate(response)

print(output)

…仅正确发射:

queryId foo

相关问题 更多 >