0

在这个例子中我是如何滥用 gflags 的?在命令行上设置标志不会覆盖默认值,但是当我根据需要设置标志并且不使用默认值(注释代码)时,它会被设置(到False)就好了。

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
4

1 回答 1

6

调用 FLAGS(argv) 进行解析。

示例用法:

  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)
于 2014-12-22T08:38:26.107 回答