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
.
There are two types of arguments a Python function can accept: positional and optional.
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With