Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse: diiference between -o and --option

I am trying to understand the argparse package and I really can't find an answer to this very simple question:

  • What is the difference between -a and --argument when adding an argument?

Sometimes, I find both in one add_argument() like here:

parser.add_argument(
        "-f", "--file",
        help="file path"
        )
like image 495
farhawa Avatar asked Jun 14 '17 22:06

farhawa


People also ask

What is option in Python?

Rust-like Option and Result types in Python, slotted and fully typed. An Option type represents an optional value, every Option is either Some and contains Some value, or NONE.

How do you add an optional argument in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How do I make Argparse argument optional in Python?

Python argparse optional argument The example adds one argument having two options: a short -o and a long --ouput . These are optional arguments. The module is imported. An argument is added with add_argument .

Why click instead of Argparse?

Click actually implements its own parsing of arguments and does not use optparse or argparse following the optparse parsing behavior. The reason it's not based on argparse is that argparse does not allow proper nesting of commands by design and has some deficiencies when it comes to POSIX compliant argument handling.


1 Answers

If both are specified, then argparse will store the value in the long form ('argument') rather than the short form ('a'). It will infer the destination, so "--foo-bar" will be stored in foo_bar.

You can mash together short forms and use a single hyphen (-af) but unlike some *NIX commands, order is important: If your argument requires a value (-f filename) then the argument must appear as the final argument of the group of short-form arguments:

cmd -af my_file   # works
cmd -fa my_file   # does not work

Compare this with the monster tar(1) which allows tar -cfC myfile.tar ./directory and will correctly sort it out as logically equivalent to tar -c -f myfile.tar -C ./directory. Also, some long forms allow the use of '=' when specifying the option tar -cf myfile.tar, versus tar -c --file=myfile.tar. You cannot use '=' on short forms.

Fortunately, python argparse doesn't care about '='. Use it or not, with short form or long form.

# All equivalent:
  cmd -af=my_file
  cmd -a -f my_file
  cmd -a -fmy_file
  cmd -afmy_file
  cmd --file my_file -a
  cmd --file=my_file -a

Does it matter? As another answer suggests, the long form can help with readability. Short form can make your power-users happier.

like image 119
pbuck Avatar answered Sep 27 '22 23:09

pbuck