Output command line arguments with argparse?

I use argparse to parse command line arguments.

To help debugging, I would like to print create a string with the arguments that were called using the Python script. Is there an easy way to do this in argparse ?

+7
python argparse
source share
2 answers

ArgumentParser.parse_args by default accepts arguments simply from sys.argv . Therefore, if you do not change this behavior (passing something else to parse_args ), you can simply print sys.argv to get all the arguments passed to the Python script:

 import sys print(sys.argv) 

Alternatively, you can also just print the namespace that parse_args returns; this way you get all the values ​​in the way the argument interpreter interpreted them:

 args = parser.parse_args() print(args) 
+11
source share

If you run argparse inside another python script , for example, when testing inside unittest , then printing sys.argv will only print the arguments to the main script, for example:

['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 repeat the argparse arguments:

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

Thanks: fooobar.com/questions/219657 / ...

+4
source share

All Articles