Waldo Bronchart Waldo Bronchart - 4 months ago 54
Python Question

Argparse optional positional arguments?

I have script which is meant to be used like this:

usage: installer.py dir [-h] [-v]

is a positional argument which is defined like this:

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

I want 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"


Try using nargs='?'

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:

optional arguments:
  -h, --help  show this help message and exit