[Tutor] File-Fetcher (cmdline-parser)

Peter Otten __peter__ at web.de
Fri Mar 15 19:18:37 CET 2013


Christopher Emery wrote:

> Hello Peter,
> 
> First let me say thanks for your feedback, please see comments /
> question below, yours starting with PO and mine starting with CE.
> 
> PO: dest determines the attribute name under which the option is
> stored. I rarely set it explicitly; instead I provide a --long-option:
> CE: Is there a advantage over on or the other?

The advantage is basically that you get a long option ;)
This makes for calls in bash scripts, say, that are easier to understand.
Also, if you make it a habit to keep long option and dest in sync (something 
you get for free if you only specify the option) you can deduce the 
attribute name used in the script from its commandline interface. If in a 
few months you want to make modifications you will know what to look for in 
the script.

> CE: Because there are options that can be added to each .add_argument
> such as help=, action= is it a good idea to set each one of them even
> if the default behavior is what you want?  I thinking future proofing
> wise.
> PO: To my eyes this is just noise.
> CE: I would agree, to me less the better as long as it can be
> understood and your not going to break something in the near future
> that will change.
> 
> CE: At the end I use a print() to see if all is being passed or not
> being passed through the cmdline, my question for you is if I want to
> access the varibles that are passed through the return args, do I just
> take the function like this:
> outside_of_functions_var = cmdline_parser()
> Does this make outside_of_functions_var a dict or list or other?
> PO: Neither a dict nor a list, it is an argparse.Namespace object. You
> can access commandline options as its attributes:
> CE: Okay, so when I use print(args.file_list) or better yet if I take
> list = args.file_list does it stay a Namespace object or does it
> change?  if it stays the same how do I access the list of files inside
> it?

While args is a Namespace instance args.file_list is a list (if you provide 
the option at least once on the commandline):

$ cat tmp_filefetcher.py
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-l', "--file-list", action="append")
args = parser.parse_args()
print("args =", args)
print("args.file_list = ", args.file_list)

$ python3 tmp_filefetcher.py 
args = Namespace(file_list=None)
args.file_list =  None

$ python3 tmp_filefetcher.py -l alpha -l beta
args = Namespace(file_list=['alpha', 'beta'])
args.file_list =  ['alpha', 'beta']




More information about the Tutor mailing list