A minimalist Python application framework
Flam provides utility functions and classes used in 99% of applications (that I write).
Currently it provides:
- Application bootstrapping.
- Flag management.
- Command-line commands.
Application bootstrapping
Typically all an application writer wants to do is run a main() function, register some flags, maybe take some action based on a command-line argument, set up logging defaults.
Releasepeace's "run" command takes care of all this:
from flam import define_flag, flags, command, run
define_flag('-l', '--long_listing', help='long listing', default=False, action='store_true')
@command def ls(path):
- if flags.long_listing:
- ...
- else:
- ...
- def main(args):
- # Some initialisation code here... ...
- if __name__ == '__main__':
- run(main)
run() will parse command line flags, call main with any remaining arguments, then finally dispatch to any commands registered with @command, in this case "ls".
Command Management
Flam provides support for both command-line flags and commands, where commands are actions passed on the command-line.
For example, the following will register an "init" command:
@command def init(path):
"""Initialise the system.""" db = sqlite3.open(path) ...
Which can then be used like so:
$ python myapp.py init somefile.db
Help is automatically generated by inspecting the registered command functions:
$ python myapp.py help Usage: myapp.py [<options>] <command> ...
- Commands:
- help [<command>]
- Display help on available commands.
- init <path>
- Initialise the system.
- Options:
-h, --help show this help message and exit --flags=FILE load flags from FILE --logging=LEVEL Â set log level to debug, info, warning, error or fatal [warning]
Flag Management
Register new flags with flam.define_flag()
. This is an alias for
optparse.OptionParser.add_option()
and thus accepts exactly the same arguments.
The underlying optparse.OptionParser
object is exposed as flam.flag_parser
.
Call flam.parse_args()
to parse command-line arguments. Defaults to
parsing sys.argv[1:].
flam.flags
is an optparse.Values() object that will contain the parsed
flag values.
The --flags=FILE flag can be used to load flag values from a file consisting of "key = value" lines. Both empty lines and those beginning with # are ignored.