In this month's Python column, learn to write your own command-line apps with the Click, Docopt, and Fire libraries.

Subscribe now

Get the highlights in your inbox every week.

Sometimes the right tool for the job is a command-line application. A command-line application is a program that you interact with and run from something like your shell or Terminal. Git and Curl are examples of command-line applications that you might already be familiar with.

Command-line apps are useful when you have a bit of code you want to run several times in a row or on a regular basis. Django developers run commands like ./manage.py runserver to start their web servers; Docker developers run docker-compose up to spin up their containers. The reasons you might want to write a command-line app are as varied as the reasons you might want to write code in the first place.

For this month's Python column, we have three libraries to recommend to Pythonistas looking to write their own command-line tools.

The @click.option() decorator declares an optional argument, and the @click.argument() decorator declares a required argument. You can combine optional and required arguments by stacking the decorators. The echo() method prints results to the console.

$ python hello.py --name='Lacey'
Hello Lacey!

Docopt

Docopt is a command-line application parser, sort of like Markdown for your command-line apps. If you like writing the documentation for your apps as you go, Docopt has by far the best-formatted help text of the options in this article. It isn't our favorite command-line app library because its documentation throws you into the deep end right away, which makes it a little more difficult to get started. Still, it's a lightweight library that is very popular, especially if exceptionally nice documentation is important to you.

Docopt is very particular about how you format the required docstring at the top of your file. The top element in your docstring after the name of your tool must be "Usage," and it should list the ways you expect your command to be called (e.g., by itself, with arguments, etc.). Usage should include help and version flags.

The second element in your docstring should be "Options," and it should provide more information about the options and arguments you identified in "Usage." The content of your docstring becomes the content of your help text.

At its most basic level, Docopt is designed to return your arguments to the console as key-value pairs. If I call the above command without specifying a name, I get a dictionary back:

$ python hello.py {'--help': False,'--version': False,'<name>': None}

This shows me I did not input the help or version flags, and the name argument is None.

But if I call it with a name, the say_hello function will execute.

$ python hello.py Jeff
Hello Jeff!

Docopt allows both required and optional arguments and has different syntax conventions for each. Required arguments should be represented in ALLCAPS or in <carets>, and options should be represented with double or single dashes, like --name. Read more about Docopt's patterns in the docs.

Fire

Fire is a Google library for writing command-line apps. We especially like it when your command needs to take more complicated arguments or deal with Python objects, as it tries to handle parsing your argument types intelligently.

Its weakness is the documentation it makes available to the console. Docstrings on your commands don't appear in the help text, and the help text doesn't necessarily identify arguments.

import fire

def say_hello(name=''):return'Hello {}!'.format(name)

if __name__ =='__main__':
fire.Fire()

Arguments are made required or optional depending on whether you specify a default value for them in your function or method definition. To call this command, you must specify the filename and the function name, more like Click's syntax:

Everywhere you see hello, substitute the name of your module but omit the .py extension. Where you see say_hello, substitute the name of your function.

Then, run pip install --editable to make your command available to the command line.

You can now call your command like this:

$ hello --name='Jeff'
Hello Jeff!

By packaging your command, you omit the extra step in the console of having to type python hello.py --name='Jeff' and save yourself several keystrokes. These instructions will probably also work for the other libraries we mentioned.

Topics

About the author

Jeff Triplett - Jeff Triplett is an open source developer and works as a software engineer, consultant, and partner at REVSYS. He is a Board of Director at The Python Software Foundation.
He occasionally blogs on his website.
Jeff joined REVSYS as an engineer in 2011. Before that, Jeff worked on Ellington CMS and Marketplace as a lead engineer at...

About the author

Lacey Williams Henschel - Lacey Williams Henschel is a software engineer with REVSYS and part of the organizing team for DjangoCon US. In the past, she's chaired DjangoCon US, organized several Django Girls workshops, taught courses for Treehouse, and written about accessibility at tech events.

Footer

The opinions expressed on this website are those of each author, not of the author's employer or of Red Hat.

Opensource.com aspires to publish all content under a Creative Commons license but may not be able to do so in all cases. You are responsible for ensuring that you have the necessary permission to reuse any work on this site. Red Hat and the Red Hat logo are trademarks of Red Hat, Inc., registered in the United States and other countries.