Created
February 26, 2024 07:28
-
-
Save alvinwan/2894c903467225d796e84cc7e962f358 to your computer and use it in GitHub Desktop.
Extract argparse information
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 | |
def get_argparse_spec_as_dict(parser): | |
""" | |
Gets the argparse spec as a dictionary. | |
This makes transformations on the argument parser a little | |
easier. | |
""" | |
arguments = [] | |
for action in parser._actions: | |
argument = {} | |
for key, value in vars(action).items(): | |
if key == 'option_strings': | |
argument[key] = list(map(str, value)) | |
continue | |
if isinstance(value, (str, int)) or value is None: | |
# These are all normal, jsonify-able values. | |
argument[key] = value | |
continue | |
if key == 'container': | |
# This is an ArgumentGroup object that we don't | |
# really need to 'export' | |
continue | |
# NOTE: This clause really only applies to the type. You | |
# could optionally keep this as a function, to use later. | |
# This is stringified to support JSONifying. | |
argument[key] = str(value) | |
arguments.append(argument) | |
return {'arguments': arguments} | |
# Normal parser definition. Note that we don't have to call parse_args | |
parser = argparse.ArgumentParser() | |
parser.add_argument('--foo', type=int, help='an integer argument') | |
parser.add_argument('--bar', type=str, help='a string argument') | |
# Get the argparse spec as JSON and print it. | |
spec = get_argparse_spec_as_dict(parser) | |
print(json.dumps(spec, indent=4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment