argparse - option with optional value

Miki Tebeka miki.tebeka at gmail.com
Thu May 17 17:26:50 EDT 2012


Greetings,

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.

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)
    ...
    if args.edit != no_edit:
        editor = args.edit or environ.get('EDITOR', 'vim')


However I get a feeling there's a better way to do that.
Any ideas?

Thanks,
--
Miki



More information about the Python-list mailing list