Print command line arguments with argparse?

Question:

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?

Asked By: becko

||

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)
Answered By: 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:eclipsepluginsorg.python.pydev_5.9.2.201708151115pysrcrunfiles.py’, ‘C:eclipse_workspacetest_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

Answered By: Noam Manos

You can get the arguments as a dict by calling vars(args)
Then you can iterate over the key-value pairs of the dict

args = parser.parse_args()
print(' '.join(f'{k}={v}' for k, v in vars(args).items()))
Answered By: Dor Meiri
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.