Last active
October 28, 2017 09:05
-
-
Save bpeterso2000/c94f374f171037f41eb2df6c81f17016 to your computer and use it in GitHub Desktop.
This file contains 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
import json | |
import sys | |
import click | |
import click._termui_impl | |
class JSONFile(click.File): | |
name = 'JSON.load' | |
def __init__(self, **kwds): | |
super(JSONFile, self).__init__(**kwds) | |
def convert(self, value, param, ctx): | |
f = super(JSONFile, self).convert(value, param, ctx) | |
if click._termui_impl.isatty(sys.stdin): | |
click.echo(ctx.get_usage()) | |
click.echo("Try `jsonclick --help' for more information.") | |
return '' | |
try: | |
return json.load(f) | |
except (json.JSONDecodeError, TypeError) as e: | |
self.fail('%s does not contain valid JSON: %s' % ( | |
click._compat.filename_to_ui(value), | |
click._compat.get_streerror(e), | |
), param, ctx) | |
return '' | |
@click.command() | |
@click.argument('jsonfile', default='-', type=JSONFile()) | |
def main(jsonfile): | |
click.echo(jsonfile) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment