argparse - option with optional value

Discussion in 'Python' started by Miki Tebeka, May 17, 2012.

  1. Miki Tebeka

    Miki Tebeka Guest

    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
     
    Miki Tebeka, May 17, 2012
    #1
    1. Advertising

  2. Miki Tebeka

    Miki Tebeka Guest

    > 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>.

    The problem with this approach is that in both cases of not specifying -e and with -e with no argument the value of args.edit is None.
     
    Miki Tebeka, May 18, 2012
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Julien ROUZIERES

    g++ -pg option and -shared option

    Julien ROUZIERES, Dec 21, 2004, in forum: C++
    Replies:
    1
    Views:
    756
    GianGuz
    Dec 21, 2004
  2. Cas
    Replies:
    5
    Views:
    814
    Kevin Jones
    Aug 28, 2006
  3. Kevin Blount

    page.aspx?option - how to detect "option"

    Kevin Blount, Nov 28, 2006, in forum: ASP .Net
    Replies:
    6
    Views:
    623
    =?Utf-8?B?RWVyYWo=?=
    Nov 28, 2006
  4. Peter Otten
    Replies:
    1
    Views:
    494
    rantingrick
    Feb 1, 2011
  5. Martin Daser

    Q: Adding Optional option to expression match

    Martin Daser, May 18, 2006, in forum: Perl Misc
    Replies:
    2
    Views:
    99
    Martin Daser
    May 18, 2006
Loading...

Share This Page