[optparse] Problem with getting an option value

Peter Otten __peter__ at web.de
Fri Apr 6 07:07:54 EDT 2007

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


More information about the Python-list mailing list