使用命令行(ssh)對Gerrit進行查詢, 官方地址:https://review.openstack.org/Documentation/cmd-query.html
程序例子
import os, json def get_patch_info(GERRIT_HOME, patch_id): cmd_str='ssh %s gerrit query --format=JSON --comments change:%d'%(GERRIT_HOME, patch_id) process = os.popen(cmd_str) output = process.readlines()[0] # 參見說明 process.close() jsn_data = json.loads(output) # 返回的是dict return jsn_data
說明:查詢結果永遠會多返回一行查詢統計的信息在最后一行, 即使查詢結果是空:
{"moreChanges": false,"runTimeMilliseconds": 80,"rowCount": 1,"type": "stats"}
如果用shell,可以使用 jq 做解析。jq 能夠對 json 結果進行格式化和挑選。
安裝 sudo apt-get install jq
ssh review.example.com gerrit query --format=JSON --patch-sets --files change:89535 | jq . > 89535-pretty.txt ssh review.example.com gerrit query --format=JSON --patch-sets --files change:89535 > 89535-pretty.txt cat 89535-pretty.txt | jq . cat 89535-pretty.txt | jq ".status" # 取出該 patch 的 status cat 89535-pretty.txt | jq ".patchSets[0].files" # 取出第一個patchSet 修改的文件信息 cat 89535-pretty.txt | jq "keys" # 列出所有key cat 89535-pretty.txt | jq "has('owner')" # 是否存在該key
以下轉自:http://blog.chinaunix.net/uid-24774106-id-3830242.html
與JSON相關的我就暫時介紹到這里,希望進一步了解jq並使用的可以去http://stedolan.github.io/jq/manual/,希望了解源碼實現的,可以去https://github.com/stedolan/jq,意料之中的事情是 作者用來flex和bison來parse json。
我們的示例JSON來自參考文獻第一篇。
用google搜索,kernalpanic中有篇文章介紹了jshon和json.sh提供了另外的思路。
參考文獻:
1 How to parse JSON string via command line on Linux
2 jq - command-line JSON processor
