Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
parser.parse_args() meaning
#1
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!
Reply
#2
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.
vinci likes this post
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  What is the meaning of k in this function? giladal 3 579 Aug-15-2020, 12:32 PM
Last Post: buran
  Here what is the meaning of span=(1,2) ,match='1'? srisrinu 1 483 Apr-27-2020, 10:22 AM
Last Post: anbu23
  What is the meaning of mutable data type? qliu 3 742 Apr-17-2020, 07:20 PM
Last Post: deanhystad
  Upper-Bound Exclusive Meaning Johnny1998 1 1,069 Aug-02-2019, 08:32 PM
Last Post: ichabod801
  Finding phrases of one semantic meaning VladislavMz 2 856 Dec-20-2018, 03:29 AM
Last Post: VladislavMz
  Meaning of some term? hsunteik 2 2,239 Dec-21-2016, 05:47 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020