Python Gflags
Python-gflags is a Python implementation of the Google command-line flags module, enabling distributed command-line systems by allowing flags to be defined across different modules. It is currently at version 3.1.2. This library is now obsolete and no longer maintained; users are strongly encouraged to migrate to `absl-py` for continued support and new features.
Warnings
- breaking The entire `python-gflags` library is deprecated and no longer actively maintained. All new development has moved to `absl-py`, specifically `absl.flags`. Users should plan to migrate to `absl-py` to receive updates and avoid unmaintained dependencies.
- breaking Version 3.1.0 introduced significant breaking changes, including: removal of `UnrecognizedFlag` (now `UnparsedFlagAccessError` can be raised for premature flag access), replacement of `DuplicateFlag` with `DuplicateFlagError`, renaming of `IllegalFlagValue` to `IllegalFlagValueError`, and moving `validators.Error` to `exceptions.ValidationError`. Several methods like `MutualExclusionValidator`, `FlagValues.AddValidator`, and `_helpers.GetMainModule` were removed.
- gotcha If `python-gflags` and `absl.flags` are both present in the same process, it can lead to two global `FLAGS` objects coexisting, causing unexpected behavior and conflicts during flag definition and parsing.
- gotcha Accessing flag values before command-line arguments have been parsed by calling `FLAGS(sys.argv)` can raise an `UnparsedFlagAccessError` in newer versions. Additionally, `FLAGS.set_default` no longer overrides the current value if the flag has already been set via command line or direct assignment.
Install
-
pip install python-gflags
Imports
- FLAGS
from gflags import FLAGS
import gflags as flags FLAGS = flags.FLAGS
- DEFINE_string
import gflags as flags flags.DEFINE_string('name', 'default', 'help string') - DEFINE_integer
import gflags as flags flags.DEFINE_integer('count', 0, 'help string')
Quickstart
import sys
import gflags as flags
FLAGS = flags.FLAGS
flags.DEFINE_string('name', 'World', 'Your name.')
flags.DEFINE_integer('age', 30, 'Your age in years.', lower_bound=0)
flags.DEFINE_boolean('debug', False, 'Enable debug output.')
def main(argv):
try:
argv = FLAGS(argv)
except flags.FlagsError as e:
print(f'{e}\nUsage: {sys.argv[0]} ARGS\n{FLAGS}')
sys.exit(1)
if FLAGS.debug:
print(f'Debug mode enabled. Non-flag arguments: {argv}')
print(f'Hello, {FLAGS.name}! You are {FLAGS.age} years old.')
if __name__ == '__main__':
main(sys.argv)