Skip to content

Commit

Permalink
pythonlib/parse_command: automatically parse json and csv output
Browse files Browse the repository at this point in the history
  • Loading branch information
petrasovaa committed May 3, 2024
1 parent 763fa05 commit a92e7fd
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions python/grass/script/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@
import string
import random
import shlex
import json
import csv
import io
from tempfile import NamedTemporaryFile
from pathlib import Path

Expand Down Expand Up @@ -543,40 +546,52 @@ def read_command(*args, **kwargs):

def parse_command(*args, **kwargs):
"""Passes all arguments to read_command, then parses the output
by parse_key_val().
by default with parse_key_val().
Parsing function can be optionally given by <em>parse</em> parameter
including its arguments, e.g.
If the command has parameter <em>format</em> and is called with
<em>format=json</em>, the output will be parsed into a dictionary.
Similarly, with <em>format=csv</em> the output will be parsed into
a list of lists (CSV rows).
::
parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
parse_command("v.db.select", ..., format="json")
or you can simply define <em>delimiter</em>
Custom parsing function can be optionally given by <em>parse</em> parameter
including its arguments, e.g.
::
parse_command(..., delimiter = ':')
parse_command(..., parse=(gs.parse_key_val, {'sep': ':'}))
Parameter <em>delimiter</em> is deprecated.
:param args: list of unnamed arguments (see start_command() for details)
:param kwargs: list of named arguments (see start_command() for details)
:return: parsed module output
"""

def parse_csv(result):
return list(csv.reader(io.StringIO(result)))

parse = None
parse_args = {}
if "parse" in kwargs:
if isinstance(kwargs["parse"], tuple):
parse = kwargs["parse"][0]
parse_args = kwargs["parse"][1]
del kwargs["parse"]

if "delimiter" in kwargs:
parse_args = {"sep": kwargs["delimiter"]}
del kwargs["delimiter"]
elif kwargs.get("format") == "json":
parse = json.loads
elif kwargs.get("format") == "csv":
parse = parse_csv

if not parse:
parse = parse_key_val # use default fn
if "delimiter" in kwargs:
parse_args = {"sep": kwargs["delimiter"]}
del kwargs["delimiter"]

res = read_command(*args, **kwargs)

Expand Down

0 comments on commit a92e7fd

Please sign in to comment.