Search code examples
pythongflags

flag not set in python-gflags


How am I misusing gflags in this example? Setting the flag on the command line doesn't override the default value, but when I set the flag as required and don't use a default value (the commented code), it gets set (to False) just fine.

import gflags
from gflags import FLAGS

#gflags.DEFINE_bool('use_cache', None, '')
#gflags.MarkFlagAsRequired('use_cache')

gflags.DEFINE_bool('use_cache', True, '')

if __name__ == '__main__':
  if FLAGS.use_cache == True:
    print 'use_cache == True'
  else:
    print 'use_cache == False'

.

~ python testflags.py --use_cache=False
use_cache == True
~ python testflags.py --help
use_cache == True

Solution

  • call FLAGS(argv) for parsing.

    EXAMPLE USAGE:

      FLAGS = gflags.FLAGS
    
      # Flag names are globally defined!  So in general, we need to be
      # careful to pick names that are unlikely to be used by other libraries.
      # If there is a conflict, we'll get an error at import time.
      gflags.DEFINE_string('name', 'Mr. President', 'your name')
      gflags.DEFINE_integer('age', None, 'your age in years', lower_bound=0)
      gflags.DEFINE_boolean('debug', False, 'produces debugging output')
      gflags.DEFINE_enum('gender', 'male', ['male', 'female'], 'your gender')
    
      def main(argv):
        try:
          argv = FLAGS(argv)  # parse flags
        except gflags.FlagsError, e:
          print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS)
          sys.exit(1)
        if FLAGS.debug: print 'non-flag arguments:', argv
        print 'Happy Birthday', FLAGS.name
        if FLAGS.age is not None:
          print 'You are a %d year old %s' % (FLAGS.age, FLAGS.gender)
    
      if __name__ == '__main__':
        main(sys.argv)