Re: parser.has_options(...)

Greg Ward <[email protected]> Thu, 1 Jul 2004 13:48:08 -0400
Newsgroups gmane.comp.python.optik.user
Message-ID <[email protected]>
On 21 June 2004, Jeremy Conlin said:
> I am writing another script using optparse because I have found it 
> very helpful.  I would like to know if the user has specified an 
> option.  If the user has specified an option and given it a value, I 
> want to do something different.  This is what I have, but it doesn't 
> work.  
> 
> parser = OptionParser(usage=usage, version='Version #:%s' %Version) 
> parser.add_option("-C", "--Cool", type="float", default=False, 
>                     help='Coolest Temperature in Fuel Region') 
> parser.add_option("-H", "--Hot", type="float", default=False, 
>                     help='Hottest Temperature in Fuel Region') 
> ... 
> 
> if parser.has_option('-C'): 
>     print 'Cool Temperature was specified %.3f' %options.Cool 
>     print 'Enter Cool Temperature code here:' 
> if parser.has_option('H'): 
>     print 'Hot Temperature was specified %.3f' %options.Hot 
>     print 'Enter Hot Temperature code here:' 

Here's the documentation for has_option():

``has_option(opt_str : string) : boolean``
    Given an option string such as ``"-q"`` or ``"--verbose"``, returns
    true if the OptionParser has an option with that option string.

This method has nothing to do with the parsed command line; it's just
for querying what options the parser knows about.

The right way to do this is:

  parser.add_option("-C", "--Cool", type="float",
                      help='Coolest Temperature in Fuel Region') 
  parser.add_option("-H", "--Hot", type="float",
                      help='Hottest Temperature in Fuel Region') 
  [...]
  (options, args) = parser.parse_args()
  [...]
  if options.Cool is None:
      print 'Cool Temperature was specified %.3f' %options.Cool 
      print 'Enter Cool Temperature code here:' 
  if options.Hot is None:
      print 'Hot Temperature was specified %.3f' %options.Hot 
      print 'Enter Hot Temperature code here:' 

(It's not necessary to specify a default value for these options, since
the default default is None.)

Although I would argue that this is the wrong user interface.  It's
highly unconventional for Unix command-line programs to fallback to
interactive operation like this, because it makes them difficult to
script.

Also, long options should conventionally be all lower case: --cool and
--hot rather than --Cool and --Hot.

        Greg
-- 
Greg Ward <[email protected]>                         http://www.gerg.ca/
Cheops' Law: Nothing *ever* gets built on schedule or within budget.


-------------------------------------------------------
This SF.Net email sponsored by Black Hat Briefings & Training.
Attend Black Hat Briefings & Training, Las Vegas July 24-29 - 
digital self defense, top technical experts, no vendor pitches, 
unmatched networking opportunities. Visit www.blackhat.com