Print all argparse arguments including defaults
Asked Answered
C

1

8

I want to log the usage of a python program which uses the argparse module. Currently, the logger records the command line usage similar to the answer given in this post. However, that only gives the command line arguments, and not including the defaults set later in argparse (which is the intended use, after all). Is there a simple way to print ALL the argparse options to create a nice, tidy usage log entry that includes the default values?

It isn't difficult to go into the argparse namespace to fetch each argument by name, but I am hoping that someone has a concise way of extracting the needed info.

In response to the accepted answer:

Great! If anyone is interest, here is my implementation with logging:

logger.info("Usage:\n{0}\n".format(" ".join([x for x in sys.argv])))
logger.debug("All settings used:") for k,v in sorted(vars(args).items()):
    logger.debug("{0}: {1}".format(k,v))
Clift answered 11/10, 2016 at 13:17 Comment(0)
P
18

I've done something similar in an application, hopefully the below snippets give you what you need. It is the call to vars that gave me a dictionary of all the arguments.

parser = argparse.ArgumentParser(description='Configure')
....
args = parser.parse_args()
......
options = vars(args)
Pedometer answered 11/10, 2016 at 13:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.