Basic Usage
We're going to create a small CLI with a single (deeply-nested) greet
command/function:
<mycli>
is the placeholder for the name of the executable (in this case it's just going to end up being python -m mypkg.cli
). topic
is a command (we're already 1 level deep!). cmd
is a subcommand of topic
. subcmd
is a subcommand of cmd
(sub-subcommand of topic
). Finally, greet
is our actual function.
Normally we would need a fair bit of boilerplate to wire this up, but we'll see how multicommand
makes this super easy.
#
SetupCreate a directory to work in, for example:
Install multicommand
:
Create the subpackage to house our parsers:
note
That's a long path. Feel free to skip over this note and continue, but if you're perplexed by this directory structure here's a high-level explanation:
Part of that path should already be looking familiar. (The topic/cmd/subcmd
part - that's no coicidence!) Basically, mypkg
is the name of what will become our installable package (i.e. we'll eventually be able to import mypkg
).
The folder mypkg/parsers
is going to be a sub-package (i.e it's going to contain an __init__.py
file - in fact, all these folders will be sub-packages). This sub-package (mypkg.parsers
) will be the thing that we pass to multicommand
, from which we'll get our configured argparse.ArgumentParser
instance.
As for the remaining folders, multicommand
will use those to create the command hierarchy that we're after.
Create the *.py
files we'll need.
#
The codeFirst, add a parser
to greet.py
:
Second, add an entrypoint (this is the module we'll run from the command line):
with the following content:
Third, there is no third step! Let's try it out!
Take a look at our greet
command:
From this we get:
#
BonusWant to add the command <mycli> topic cmd ungreet ...
to say goodbye?
Add the module:
note
Notice that since we want to create the command <mycli> topic cmd ungreet ...
we're creating the module <sub-pkg-that-we'll-pass-to-multicommand>/topic/cmd/ungreet.py
, where in this case <sub-pkg-that-we'll-pass-to-multicommand>
is mypkg/parsers/
with contents:
The new command is automatically added!:
Try it out: