argparse, tell if arg was defaulted
Jean-Michel Pichavant
jeanmichel at sequans.com
Tue Mar 15 14:20:58 EDT 2011
Neal Becker wrote:
> Robert Kern wrote:
>
>
>> On 3/15/11 9:54 AM, Neal Becker wrote:
>>
>>> Is there any way to tell if an arg value was defaulted vs. set on command
>>> line?
>>>
>> No. If you need to determine that, don't set a default value in the
>> add_argument() method. Then just check for None and replace it with the
>> default value and do whatever other processing for the case where the user
>> does not specify that argument.
>>
>> parser.add_argument('-f', '--foo', help="the foo argument [default: bar]")
>>
>> args = parser.parse_args()
>> if args.foo is None:
>> args.foo = 'bar'
>> print 'I'm warning you that you did not specify a --foo argument.'
>> print 'Using default=bar.'
>>
>>
>
> Not a completely silly use case, actually. What I need here is a combined
> command line / config file parser.
>
> Here is my current idea:
> -----------------------------
>
> parser = OptionParser()
> parser.add_option ('--opt1', default=default1)
>
> (opt,args) = parser.parse_args()
>
> import json, sys
>
> for arg in args:
> print 'arg:', arg
> d = json.load(open (arg, 'r'))
> parser.set_defaults (**d)
>
> (opt,args) = parser.parse_args()
> -----------------------
>
> parse_args() is called 2 times. First time is just to find the non-option args,
> which are assumed to be the name(s) of config file(s) to read. This is used to
> set_defaults. Then run parse_args() again.
>
>
Is that what you want ?
"user CLI > json defaults > script default"
If so, your idea seems good.
Otherwise
"--opt1" in sys.argv
would tell you if an option has been specified through the CLI. But it
seems to me anti-pattern. You should not need to parse the CLI, that's
the purpose of using optparse.
JM
More information about the Python-list
mailing list