A command-line application is an application that you can run from your terminal (e.g. from bash).
In this guide we will review what makes a good command-line application and see how to implement one easily using python 3.
The first chapter focuses on inputs, and in particular, how to get inputs through the command-line interface.
- What is a command-line interface?
- The argument vector
- How to write a CLI in python? (using
- Good practices and conventions
- Design a great help text
- Enable auto-completion
- How to structure your code?
The second chapter focuses on ouputs. There are two standard streams and it is important to choose the right one for proper interoperability with the script's environment.
stderrand unix pipelines
- Use standard error through the logging module
- Only use
- Improve terminal experience
- Securely prompt for passwords
- Colors, the cross-platform way
- Progress bars that work
In chapter 3, we turn to another form of input/output: the signals.
- Interrupt a process with
- Pause and resume a process with
- Handle signals using the
The last and upcoming chapter will tackle the packaging and redistribution of your application.
Here are additional tips that didn't fit into the previous articles and that aren't big enough to make it into their own.
stdin instead of
If the goal of your script is to transform a bunch of text lines (like
wc do), you should read those lines from
stdin instead of forcing the user to use a real file.
Why? Because that way your script can be used in combination with others through pipes. When someone wants to use your script with a file on disk,
cat can be used to pipe the file into the script's
stdin. Here's an example:
cat file.txt | grep "scripting.tips" | myscript
In the command above, the file
file.txt is filtered by
grep to keep only the lines that contain "scripting.tips" and then the result is sent to
Choose your exit codes
Each process can terminate with an exit code. The convention is that
0 means success, while non-zero exit codes mean that an error occured. According to sys.exit documentation, the unix convention is to use
2 for a command-line syntax error and
1 for any other error. Here's how to use it:
import sys # ... if error: sys.exit(1)