[Python-Dev] PEP 389: argparse - new command line parsing module (original) (raw)
Steven Bethard steven.bethard at gmail.com
Mon Sep 28 21:57:08 CEST 2009
- Previous message: [Python-Dev] PEP 389: argparse - new command line parsing module
- Next message: [Python-Dev] PEP 389: argparse - new command line parsing module
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Mon, Sep 28, 2009 at 12:22 PM, Brett Cannon <brett at python.org> wrote:
On Mon, Sep 28, 2009 at 08:49, Steven Bethard <steven.bethard at gmail.com> wrote:
On Mon, Sep 28, 2009 at 8:27 AM, Steven D'Aprano <steve at pearwood.info> wrote:
On Tue, 29 Sep 2009 12:28:39 am Steven Bethard wrote:
* Would you like argparse to grow an addgetoptarguments method (as in my other post)?
0
* If argparse grew an addgetoptarguments, would you still want to keep getopt around? And if so, why? Simplicity of the learning curve. Using it is as simple as: getopt.getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]) You forgot the for-loop, nested if/else statements and type conversions. ;-) =) I do wonder if people who are advocating for getopt sticking around realize how much extra code must be written to make sure what it gives back to you is in some sane manner. Let's take
getopt.getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
as an example and simply assume that 'alpha' takes a string as an argument and that it's required and that 'beta' is a boolean flag. To pull everything out you could do:: options, args = getopt.getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]) optionsdict = dict(options) alpha = optionsdict.get('-a', optionsdict.get('--alpha', '')) beta = '-b' in optionsdict or '--beta' in optionsdict main(alpha, beta, args) Obviously if one of the getopt supporters has a better way of doing this then please speak up. Now, Steven, can you show how best to do this in argparse?
Here's the same option parsing in argparse:
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--alpha')
parser.add_argument('-b', '--beta', action='store_true')
args = parser.parse_args()
main(args.alpha, args.beta)
Or if those final positional arguments were actually meaningful, then you would add one more argument like this::
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--alpha')
parser.add_argument('-b', '--beta', action='store_true')
parser.add_argument('gammas', nargs='*')
args = parser.parse_args()
main(args.alpha, args.beta, args.gammas)
Steve
Where did you get that preposterous hypothesis? Did Steve tell you that? --- The Hiphopopotamus
- Previous message: [Python-Dev] PEP 389: argparse - new command line parsing module
- Next message: [Python-Dev] PEP 389: argparse - new command line parsing module
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]