Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse optional positional arguments?

I have a script which is meant to be used like this: usage: installer.py dir [-h] [-v]

dir is a positional argument which is defined like this:

parser.add_argument('dir', default=os.getcwd()) 

I want the dir to be optional: when it's not specified it should just be cwd.

Unfortunately when I don't specify the dir argument, I get Error: Too few arguments.

like image 363
Waldo Bronchart Avatar asked Dec 18 '10 20:12

Waldo Bronchart


People also ask

Can positional arguments be optional?

There are two types of arguments a Python function can accept: positional and optional.

How do you make an argument optional in Argparse?

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

What are positional arguments?

Positional arguments are arguments that can be called by their position in the function call. Keyword arguments are arguments that can be called by their name. Required arguments are arguments that must passed to the function. Optional arguments are arguments that can be not passed to the function.

How do you use positional arguments in Python?

Positional ArgumentsThe first positional argument always needs to be listed first when the function is called. The second positional argument needs to be listed second and the third positional argument listed third, etc. An example of positional arguments can be seen in Python's complex() function.


1 Answers

Use nargs='?' (or nargs='*' if you need more than one dir)

parser.add_argument('dir', nargs='?', default=os.getcwd()) 

extended example:

>>> import os, argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('-v', action='store_true') _StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None) >>> parser.add_argument('dir', nargs='?', default=os.getcwd()) _StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None) >>> parser.parse_args('somedir -v'.split()) Namespace(dir='somedir', v=True) >>> parser.parse_args('-v'.split()) Namespace(dir='/home/vinay', v=True) >>> parser.parse_args(''.split()) Namespace(dir='/home/vinay', v=False) >>> parser.parse_args(['somedir']) Namespace(dir='somedir', v=False) >>> parser.parse_args('somedir -h -v'.split()) usage: [-h] [-v] [dir]  positional arguments:   dir  optional arguments:   -h, --help  show this help message and exit   -v 
like image 177
Vinay Sajip Avatar answered Oct 07 '22 10:10

Vinay Sajip