Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create a wider argument parser for better options on --help
def main(args):
pass
def make_wide(formatter, width=120, max_help_position=42):
"""
Increase space between arguments and help text, if possible.
See: https://stackoverflow.com/questions/5462873/
"""
try:
# ensure formatter can be used
kwargs = {"width": width, "max_help_position": max_help_position}
formatter(None, **kwargs)
# return function to create formatter
return lambda prog: formatter(prog, **kwargs)
except TypeError:
# return originally sized formatter
return formatter
if __name__ == "__main__":
args = {
("-v", "--version"): {
"action": "version", version="v1.0",
},
("-d", "--data"): {
"type": str, "metavar": "PATH", "required": True,
"help": "path to the input data file"
},
("-o", "--out"): {
"type": str, "metavar": "PATH",
"help": "path to write out the results to"
},
("-p", "--plot"): {
"action": "store_true",
"help": "visualize the generated graph after exporting it",
},
}
parser = argparse.ArgumentParser(
formatter_class=make_wide(argparse.ArgumentDefaultsHelpFormatter)
)
for pargs, kwargs in args.items():
if isinstance(pargs, str):
pargs = (pargs,)
parser.add_argument(*pargs, **kwargs)
args = parser.parse_args()
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment