Python Forum

Full Version: parser.parse_args() meaning
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This is a simple question, but I'm asking it anyway, because I can't figure out the answer by myself:
why do we need the args = parser.parse_args() after setting up the arguments in a python program?

So the example would be something like:
from argparse import ArgumentParser
parser = ArgumentParser(description='Get the current weather information for your zipcode')
parser.add_argument('zip', help='zip/postal code to get weather for')
parser.add_argument('--country', '-c', default='us', help='country zip/postal belongs to, default is "us"')

args = parser.parse_args()
args is a random variable, so any one would do. So an object needs to be created, whatever that name is. So how does that work actually? Without creating the object args (if object is correct in this context), the help menu is not going to be displayed.

Thanks!
The normal way a Python program receives the command line arguments is in the list sys.argv. This list receives any arguments from the command line. No check is done on these arguments or the command line switches. You can call any Python program with the following command line
python myprogram.py foo bar baz --spam=eggs -d oops
When you are using the argparse module you are narrowing the set of command lines that the program considers as valid. The valid syntax is described by the parser configuration and the call to parser.parse_args() will examine the contents of the list sys.argv and transform this list into a 'namespace' instance wich is the args object caught by the program as the return value. In the meantime, the call rejects any command line syntax that doesn't fulfill the specification of the argparse parser. This namespace object has a semantics defined by the program while sys.argv's semantics is merely a split of the command line arguments.
Thank you for the explanation. I had no idea, that you can write superfluous arguments that are otherwise ignored. That makes more sense to me.