Fetching Gerrit SSH output in python

1.2k Views Asked by At

So I am using plumbum to execute the ssh command against gerrit, but I cant seem to be able to pull the output in as a json dictionary.

eg: ssh abc.xyz.com gerrit query --patch-sets --format=json commit:12345678

The output of this also dumps the below lines: type: abcd rowCount: integer runTimeMilliseconds: 123 moreChanges: ABCD

I feel this is also another dictionary.

So, is there anyway to pull the output of the ssh command into a python dictionary?

Ref: https://review.openstack.org/Documentation/cmd-query.html

3

There are 3 best solutions below

0
On

Here is how I got it to work:

data = ssh["abc.xyz.com",
    "gerrit",
    "query",
    "--patch-sets",
    "--format=JSON",
    "commit:",
    "12345678"]()

data2 = data[:data.rfind('{')]

Is there a better solution?

1
On

To get an answer in JSON format you need to change the "--format=text" option to "--format=json":

ssh abc.xyz.com gerrit query --patch-sets --format=json commit:12345678
0
On

The query result can potentially return multiple changes, each of which will be on a separate line, separated by newlines. The last line of the result is a summary, which includes a hint about whether there are more results (beyond the limit set either server side or by a limit option on your query).

In your case, you're querying for a single commit sha1 so you only get one result, but it still includes the summary line.

It should be possible to convert the result to a dict by splitting the output on newlines and converting each line separately, for example:

import json
data = ssh["abc.xyz.com",
    "gerrit",
    "query",
    "--patch-sets",
    "--format=JSON",
    "commit:",
    "12345678"]()
data2 = json.loads(data.split()[0])