Pythonids: Command Line interfaces

in #programming7 years ago

Pythonids: Command Line interfaces

With python (as with most desktop based programming languages) writing a command line interface to your script is easy. Python provides several methods out of the box that have a lot of power. However writing good, easy to use command line interfaces is not quite as easy.

Whilst Python has had optparse since version 2.3 and argparse since version 3.2 one disadvantage of these modules is that they do not allow you to nest your cli commands.

click on the other hand is a third party package designed with the express purpose of easily creating composable command line interfaces, primarily using Pythons decorator syntactic sugar.

Mouse/Click

Installing click

If you are using virtualenv's for your python development (and if you are not then you should be) then installing click is simply done with:

$ pip install click

click Examples

For a given tool we are creating we may want to have several different functions. Examples of this are git (with git add, git commit, git push etc) and apt (with apt update, apt upgrade and others).

For a fairly standard python package with a setuptools setup.py console_script entry point referencing the function cli we can build up our command fairly simply using the decorator syntax as follows. Assuming we are building cli for an apt clone called parkage then we can do

coloured python code

Then running the following on the command line will give us:

$ parkage --help
Usage: parkage [OPTIONS] COMMAND [ARGS]...

Options:
  --version  Show the version and exit.
  --help     Show this message and exit.

Commands:
  update   Update the local package info
  upgrade  Upgrade packages

Other features

I have barely touched the surface of click's capabilities here, and much more can be read about it at their web site. Some other notable features include multi-command chaining and pipelines, user input prompts (password etc), ANSI colours for screen output, launching editors and default programs for URL's and images, progress bars and much more.

Takeaway

If your needs are simple then argparse will do the job, although in these situations I still like the decorator syntax for click. If you get more complicated cli designs then the power of click can simplify the process of implementing your design significantly.

Sort:  

Resteemed your article. This article was resteemed because you are part of the New Steemians project. You can learn more about it here: https://steemit.com/introduceyourself/@gaman/new-steemians-project-launch

The @OriginalWorks bot has determined this post by @gjcooper to be original material and upvoted(1.5%) it!

ezgif.com-resize.gif

To call @OriginalWorks, simply reply to any post with @originalworks or !originalworks in your message!

Coin Marketplace

STEEM 0.27
TRX 0.13
JST 0.032
BTC 62737.73
ETH 2925.66
USDT 1.00
SBD 3.50