I’m creating a python script with usage in the same style as pacman in Arch Linux, summarized by:
prog <operation> [options] [targets]
- operations are of the form -X (hyphen, uppercase letter), and one is required when calling the script.
- options are of the form -x (hyphen, lowercase letter), and can mean different things for different operations.
For example:
pacman -Syumeans perform thesyncoperation withrefreshandsysupgradeoptions, upgrading the entire system with fresh packages.pacman -Qumeans perform thequeryoperation with theupgradesoption, listing all outdated packages.pacman -Ss <arg>means perform thesyncoperation with thesearchoption, which expects another argument as the pattern to search for in the sync packages.
The punchline:
I’ve been looking into the argparse library for python, trying to figure out how to implement this. I’ve run into some problems/design issues so far:
argparseonly accepts hyphen-prefixed arguments as optional arguments. All my “operations” would show up as optional arguments, when one is definitely required.- I could make my script have one “positional”/required argument, which would be the operation (I would have to switch operations to words, like
upgradeoradd), followed by optional arguments. This, however, still wouldn’t solve the same-option-symbol-working-differently issue, and also wouldn’t let me easily list all the supported operations in the--helptext.
What’s the smoothest way to handle this argument parsing? I’m not against changing my command’s usage, but as I said above, it doesn’t seem to help my situation as far as I can tell.
Thanks
So I found this support for sub-commands buried in the argparse help. It’s exactly what I need, with the only caveat being I am not using
-Xas the format for operations; I am just using words likeaddandsearchinstead.For completeness here’s an example of using sub-parsers from the link above: