Skip to content

Instantly share code, notes, and snippets.

@bloodearnest
Last active June 3, 2021 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bloodearnest/277cecf783fb4112f4030da8e18c3897 to your computer and use it in GitHub Desktop.
Save bloodearnest/277cecf783fb4112f4030da8e18c3897 to your computer and use it in GitHub Desktop.
Example snippet for a reusable action cli parsing code, with optional validation
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