Created
November 16, 2016 16:31
-
-
Save mpitid/8856ea14facf9c5e84453e3fed541aba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import json | |
import yaml | |
import argparse | |
import functools | |
def main(args): | |
opts = parse_cli(args[1:]) | |
reader = json.load if opts.reverse else yaml.load | |
json_encoder = functools.partial(json.dumps, separators=(',', ':')) | |
writer = yaml.safe_dump if opts.reverse else json_encoder | |
conversion = lambda fd: sys.stdout.write(writer(reader(fd)) + '\n') | |
if opts.files is None: | |
files = [sys.stdin] | |
action = conversion | |
else: | |
files = opts.files | |
action = lambda fn: with_file(fn, conversion) | |
for fd in files: | |
try: | |
action(fd) | |
except KeyboardInterrupt: | |
return 1 | |
except Exception as err: | |
sys.stderr.write('ignoring error %s\n', err) | |
sys.stderr.flush() | |
return 0 | |
def with_file(filename, action): | |
with open(filename, 'rb') as fd: | |
return action(fd) | |
def parse_cli(args): | |
parser = argparse.ArgumentParser( | |
description='convert from YAML to JSON and back') | |
parser.add_argument( | |
'-r', '--reverse', | |
action='store_true', | |
help='convert from JSON to YAML') | |
parser.add_argument( | |
'files', | |
nargs='*', | |
metavar='file', | |
help='filenames to convert (default STDIN)') | |
return parser.parse_args(args) | |
if __name__ == '__main__': | |
sys.exit(main(sys.argv)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment