I am trying to use both argparse and logging modules in python. I have a program that I run that has a lot of possible options and I've successfully implemented the argparse module to handle this task.
I'd like to keep a record of the values each option has when the program is run and send it to a log file. I tried the following couple of things, and I included the associated error I encounter as a comment beneath it.
parser = argparse.ArgumentParser()
parser.add_argument('input', action="store", default='fort.13', type=str)
args = parser.parse_args()
# First try:
logging.info("Input args: " + args)
# TypeError: cannot concatenate 'str' and 'Namespace' objects
# Second try:
for x in args:
logging.info(x)
# TypeError: 'Namespace' object is not iterable
What is the proper way to do this?
I would use a print call like the following print(' {} {}'. format(arg, getattr(args, arg) or '')) with getattr(args, arg) or '' being the essential difference to your version to prevent the word 'None' from being printed in case of unused optional parameters.
Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more integers, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.
After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser.
You can use vars
to get the attributes of your parsed arguments:
for arg, value in sorted(vars(args).items()):
logging.info("Argument %s: %r", arg, value)
This is detailed in the docs.
logging.info("Input args: %r", args)
Just dumps whole Namespace
object containing all arguments in one line in log.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With