Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: argparse optional arguments without dashes

I would like to have the following syntax:

python utility.py file1 FILE1 file2 FILE2 

where file1 and file2 are optional arguments. It is simple to make it working with this syntax:

python utility.py --file1 FILE1 --file2 FILE2 

using

parser.add_argument('--file1',type=file) parser.add_argument('--file2',type=file) 

however, if I remove the dashes, argparse starts to interprete it as a positional rather than optional argument...

In other words, is it possible to specifically tell argparse whether an argument is optional or positional so that I can have optional parameters without the dashes?

like image 810
jvm Avatar asked Jul 03 '12 12:07

jvm


People also ask

How do you add an optional argument in Argparse?

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

What does Store_true mean?

2. I would add this: store_true means if true was specified then set param value but otherwise leave it to None. If default was also specified then param is set to that value instead of leaving it to None.

What does Nargs do in Argparse?

Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.


1 Answers

There is no way to get argparse to do this for you. However, you can make argparse accept any number of positional arguments:

parser.add_argument('FILES',nargs='*') options=parser.parse_args() file1,optional_files=options.FILES[0],options.FILES[1:] 

Of course, you may want to add some checks to make sure that at least 1 file was given, etc.

EDIT

I'm still not 100% sure what you want here, but if file1 and file2 are literal strings, you can work around that a little bit by preprocessing sys.argv. Of course, this will still format your help message strangely, but you can always add an epilog explaining that either form is OK:

import argparse import sys  mangle_args=('file1','file2') arguments=['--'+arg if arg in mangle_args else arg for arg in sys.argv[1:]]  parser=argparse.ArgumentParser() parser.add_argument('--file1') parser.add_argument('--file2') options=parser.parse_args(arguments) 
like image 196
mgilson Avatar answered Sep 20 '22 06:09

mgilson