Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print command line arguments with argparse?

I am using argparse to parse command line arguments.

To aid debugging, I would like to print a line with the arguments which with the Python script was called. Is there a simple way to do this within argparse?

like image 888
becko Avatar asked Jan 25 '16 12:01

becko


People also ask

How do you print parser arguments in 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.

How do you pass arguments to Argparse?

To add your arguments, use parser. add_argument() . Some important parameters to note for this method are name , type , and required . The name is exactly what it sounds like — the name of the command line field.


2 Answers

ArgumentParser.parse_args by default takes the arguments simply from sys.argv. So if you don’t change that behavior (by passing in something else to parse_args), you can simply print sys.argv to get all arguments passed to the Python script:

import sys
print(sys.argv)

Alternatively, you could also just print the namespace that parse_args returns; that way you get all values in the way the argument parser interpreted them:

args = parser.parse_args()
print(args)
like image 199
poke Avatar answered Oct 19 '22 19:10

poke


If running argparse within another python script (e.g. inside unittest), then printing sys.argv will only print the arguments of the main script, e.g.:

['C:\eclipse\plugins\org.python.pydev_5.9.2.201708151115\pysrc\runfiles.py', 'C:\eclipse_workspace\test_file_search.py', '--port', '58454', '--verbosity', '0']

In this case you should use vars to iterate over argparse args:

parser = argparse.ArgumentParser(...
...
args = parser.parse_args()
for arg in vars(args):
    print arg, getattr(args, arg)

Thanks to: https://stackoverflow.com/a/27181165/658497

like image 26
Noam Manos Avatar answered Oct 19 '22 18:10

Noam Manos