[optparse] Problem with getting an option value

Mel Wilson mwilson at the-wire.com
Fri Apr 6 11:30:57 EDT 2007


Peter Otten wrote:
> Lucas Malor wrote:
> 
>> Hello all. I'm trying to do a little script. Simply I want to make a list
>> of all options with them default values. If the option is not specified in
>> the command line, the script must try to read it in a config.ini file. If
>> it's not present also there, it must set the default value.
>>
>> The problem is I maked a simple list for this:
>>
>> optname = [
>>   [ "delete",         False ],
>>   [ "file",   "file" ],
>>   [ "dir",    "" ],
>>
>> But I must check that the option was specified in command line:
>>
>> (options, args) = parser.parse_args()
>> for opt in optname :
>>   if not options.opt[0] :
>>     # read the options from config.ini
>>
>> The problem is options is an instance, so options."delete", for example,
>> is wrong; I should pass options.delete . How can I do?
> 
> Use getattr():
> 
> for name, default_value in optname:
>     if getattr(options, name) == default_value:
>         value = ... # read value from config file
>         setattr(options, name, value)
>         
> Personally, I would always read the config file, use the values found there
> to set up the parser and avoid such post-proc

But then, if the command-line value == the default_value the program 
will try to get a value from the config file.  If the config file 
overrides the defaults, then the command line can't re-override.

Stuck with this, I usually initialize with None, then after all the 
option sources have been done, set anything that's still None to the 
default.  It's not tidy.

If even None could be a valid value, then a new None:

class LikeNothingElse:
     '''Not a reasonable option value for anything'''
# ... various code
option_a = LikeNothingElse
option_b = LikeNothingElse
# ... process all the option sources
if option_a == LikeNothingElse:
     option_a = None


	Mel.




More information about the Python-list mailing list