Skip to content

Instantly share code, notes, and snippets.

@rmartinjak
Last active November 12, 2015 14:24
Show Gist options
  • Save rmartinjak/3683b83ff202c5f4f4e2 to your computer and use it in GitHub Desktop.
Save rmartinjak/3683b83ff202c5f4f4e2 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""Interface to a dict stored as json, useful for shell scripts."""
import argparse
import json
parser = argparse.ArgumentParser(description="set/list/get dict contents")
parser.add_argument("file", metavar="FILE", nargs=1, help='Path to dict file')
parser.add_argument("command", metavar="CMD", nargs=1,
help='Available: set, keys, items, get, del')
parser.add_argument("args", metavar="ARGS", nargs="*")
ns = parser.parse_args()
command = ns.command[0]
def dump(obj, fp):
json.dump(obj, fp, sort_keys=True, indent=4, separators=(',', ': '))
print("", file=fp)
d = {}
try:
with open(ns.file[0]) as f:
d = json.load(f)
except FileNotFoundError:
if command not in ("set"):
raise
if command == "set":
d[ns.args[0]] = ns.args[1]
with open(ns.file[0], "w") as f:
dump(d, f)
elif command == "keys":
for s in sorted(d.keys()):
print(s)
elif command == "items":
for k, v in sorted(d.items()):
print(k, "->", v.replace('\n', '\\n').replace('\t', '\\t'))
elif command == "get":
print(d[ns.args[0]])
elif command == "del":
del d[ns.args[0]]
with open(ns.file[0], "w") as f:
dump(d, f)
else:
print(parser.format_help())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment