3 ms·
My favorite library for this is docopt[0], which parses the docstring at the top of your script. It’s a lot easier for people reading your code to see the usage
by rjeli 7y ago
My favorite library for this is docopt[0], which parses the docstring at the top of your script. It’s a lot easier for people reading your code to see the usage up front rather than scrolling to the bottom and finding your main() and reading the argparse calls:
#!/usr/bin/env python3
“””
Usage: ./myscript.py <arg> [<optionalarg>]
“””
from docopt import docopt
if __name__ == ‘__main__’:
args = docopt(__doc__)
print(args[‘<arg>’], args[‘<optionalarg>’] or ‘foo’)
[0]: https://github.com/docopt/docopt https://github.com/docopt/docopt
- orf 7y agoFor really, really basic things docopt is good. But you tend to re-invent the wheel when you need to do something other than the basic parsing it supports. The click docs have a good section[1] on this: > On top of that docopt is restricted to basic parsing. It does not handle argument dispatching and callback invocation or types. This means there is a lot of code that needs to be written in addition to the basic help page to handle the parsing results. 1. http://click.palletsprojects.com/en/7.x/why/#why-not-docopt-etc http://click.palletsprojects.com/en/7.x/why/#why-not-docopt-...
- kissgyorgy 7y agodocopt seems like a good idea at first, but you will hit a limitation sooner or later. Not with Click.
- ufmace 7y agoThat's what I came in here to mention. I mostly write small, personal utilities with a max of 5-10 commands and a few parameters, and I think click's architecture is too strange and complex. Docopt is simple and clear, doesn't do anything more than I need, and leaves me free to architect the rest of the script however seems best. It also works the same in a bunch of languages. I do concede that click may be better for CLI apps that grow to tens of thousands of LOC and involve multiple full-time developers. I've never built one that big though. I also worry a bit that docopt doesn't seem to have gotten much attention in a while. It's basically complete, so shouldn't matter, but still.
- Rotareti 7y agoDocopt is a killer arg parser for build scripts. I drop a doc-string like this one in every build script and get the command line interfaces for free: """ Install: pipenv install --dev Usage: make.py [<command>] [options] Commands: build Build wheel. push Push wheel to pypi. test Run tests. bump Run interacitve bump sequence. git Run interactive git sequence. Options: -h, --help Show this screen. """