argparse - option with optional value
Ben Finney
ben+python at benfinney.id.au
Thu May 17 20:08:44 EDT 2012
Miki Tebeka <miki.tebeka at gmail.com> writes:
> I'd like to have an --edit option in my program. That if not specified
> will not open editor. If specified without value will open default
> editor ($EDITOR) and if specified with value, assume this value is the
> editor program to run.
So, two rather separate tasks: handle the command-line option, and start
the editor.
> The way I'm doing it currently is:
> ...
> no_edit = 'no-edit'
> parser.add_argument('-e', '--edit', help='open editor on log', nargs='?',
> default=no_edit)
There is a built-in “no value specified” value in Python: the None
singleton. The ‘argparse’ library uses this for the argument default
already, so you don't need to fuss with your own special handling
<URL:http://docs.python.org/library/argparse.html#default>.
So the above becomes::
parser.add_argument('-e', '--edit', help='open editor on log', nargs='?')
> ...
> if args.edit != no_edit:
and this test becomes the familiar test against None::
if args.edit is not None:
> editor = args.edit or environ.get('EDITOR', 'vim')
This will work fine, AFAICT.
--
\ “But it is permissible to make a judgment after you have |
`\ examined the evidence. In some circles it is even encouraged.” |
_o__) —Carl Sagan, _The Burden of Skepticism_, 1987 |
Ben Finney
More information about the Python-list
mailing list