Last active
June 3, 2021 09:22
-
-
Save bloodearnest/277cecf783fb4112f4030da8e18c3897 to your computer and use it in GitHub Desktop.
Example snippet for a reusable action cli parsing code, with optional validation
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
import argparse | |
import json | |
from pathlib import Path | |
class ActionConfig: | |
def __init__(self, validator=None): | |
self.validator = validator | |
def __call__(self, file_or_string): | |
path = Path(file_or_string) | |
try: | |
if path.exists(): | |
with path.open() as f: | |
config = json.load(f) | |
else: | |
config = json.loads(file_or_string) | |
except json.JSONDecodeError as exc: | |
raise argparse.ArgumentTypeError(f"Could not parse {file_or_string}\n{exc}") | |
if self.validator: | |
try: | |
self.validator(config) | |
except Exception as exc: | |
raise argparse.ArgumentTypeError(f"Invalid action config:\n{exc}") | |
return config | |
@classmethod | |
def add_to_parser(cls, parser, help="Config for action", validator=None): | |
parser.add_argument( | |
"--config", | |
required=True, | |
help=help, | |
type=cls(validator), | |
) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
ActionConfig.add_to_parser(parser) | |
print(parser.parse_args()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment