Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log the values of argparse in python

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?

like image 297
JBWhitmore Avatar asked Jul 20 '12 01:07

JBWhitmore


People also ask

How do you print args from Argparse Python?

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.

What does Argparse return?

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.

What does Argparse ArgumentParser () do?

After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser.


2 Answers

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.

like image 50
Ned Batchelder Avatar answered Nov 07 '22 07:11

Ned Batchelder


logging.info("Input args: %r", args)

Just dumps whole Namespace object containing all arguments in one line in log.

like image 35
industryworker3595112 Avatar answered Nov 07 '22 05:11

industryworker3595112