argparse, tell if arg was defaulted

Neal Becker ndbecker2 at gmail.com
Tue Mar 15 13:46:50 EDT 2011


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.




More information about the Python-list mailing list