It would have shaved off another 15-20 lines from the 503 line example ;-)
It would have shaved off another 15-20 lines from the 503 line example ;-)
First, it allows the user to abbreviate flags. They can pass --fl and it will be interpreted as --flag, assuming no other flag shares the same prefix.
This sucks for maintainability: add a new flag and any abbreviation for a previously existing flag that shares the same prefix will now stop working, breaking user workflows.
Since Python 3.5 there's the allow_abbrev parameter that allows disabling this behaviour, but then you also lose the ability to combine multiple single-character flags (so you can't pass e.g. '-Ev' any more, and would have to pass '-E -v' instead[1].
The other issue is that it's tedious to keep all the .add_argument calls readable, while maintaining a reasonable maximum line length.
Click => command line interface creation kit.
Ironic little name...
It’s a magical idea if you haven’t seen it. You just write the help text and it automatically creates the argument parsing code.
import argparse
def add_file(file):
print('Added ' + file)
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title='Sub Commands')
# add parser
add_parser = subparsers.add_parser('add', help='Add a file')
add_parser.add_argument('file', help='File to add')
add_parser.set_defaults(func=lambda args: add_file(args.file))
args = parser.parse_args()
args.func(args)
[1] https://docs.python.org/3/library/argparse.html#sub-commandsThere are cases where it is not flexible enough but it is good for quick and dirty little scripts because:
* you use the docstring to generate the args. This way you always have a minimum usage that is valid
* Argument parsing is a bit more limited than doimg it yourself, but everything you usually need is there
* Docopt is exists not only for Python, but many other languages implemented it too.