Join us

Making a CLI Application in Python

0_uUGf6jgTYs8lJnvP.jpeg

This past week I learned how to implement a CLI application so I thought about sharing this knowledge with you. But first, what exactly is a CLI?

The Command Line Interface (CLI) is a text-based interface that is used to operate software and operating systems while allowing the user to respond to visual prompts by typing single commands into the interface and receiving a reply in the same way.

CLI allows a user to perform tasks by entering commands. Its working mechanism is very easy, but it is not user friendly. Users enter the specific command, press “Enter”, and then wait for a response. After receiving the command, the CLI processes it accordingly and shows the output/result on the same screen; command line interpreter is used for this purpose.

Why use a CLI instead of a GUI?

Most people will never use command line interfaces, however there are some reasons why you could use CLI over a traditional GUI application.

  1. Less Resources
    It is not a secret that the text-based program needs very little resources of your computer. This means that with CLI you can do similar tasks with minimum resources.
  2. Repetitive Tasks Friendly
    GUI has developed well over the years. But, the operating system may not give you all the menus and buttons to perform all tasks. One of the reasons is safety. This leaves you overwhelmed if you have to do repetitive tasks. For example, when you have to handle hundreds of files within a folder, CLI enables you to use a single command to do automate the repetition easily.
  3. Powerful
    Most operating systems today prevent you from messing up the system’s core process. You won’t be able to perform certain tasks which are system protected. However, with CLI, you will have full control over your system.

CLI Parsers in Python

Photo by David Clode on Unsplash

  • Argparse — The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
  • Click — Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It’s the “Command Line Interface Creation Kit”. It’s highly configurable but comes with sensible defaults out of the box.
  • Docopt — A lightweight python package for creating command line interface easily by parsing POSIC-style or Markdown usage instructions. Docopt uses conventions that have been used for years in formatting help messages and man page for describing a command line interface. An interface description in docopt is such a help message, but formalized.
  • Clint —It incorporates everything you need in creating a CLI. It supports colors, awesome nest-able indentation context manager, supports custom email-style quotes, has an awesome Column printer with optional auto-expanding columns and so on.
  • Cement — Cement is an advanced application framework for Python, with a primary focus on Command Line Interfaces (CLI). Its goal is to introduce a standard, and feature-full platform for both simple and complex command line applications as well as support rapid development needs without sacrificing quality. Cement is flexible, and its use cases span from the simplicity of a micro-framework to the complexity of a mega-framework.
  • And many others!! These are just some of the frameworks and interpreters I researched, but there are many options out there. Explore the one that best suits your needs!

Building a CLI

Photo by Athul Cyriac Ajay on Unsplash

For this tutorial I decided to use Argparse because it is Python’s standard library module for implementing CLI applications, however, the majority of the CLI libraries and frameworks work in a similar manner.

Step 1: Import argparse and create an ArgumentParser object.

These are some of the most common parameters passed to the object. You can search the documentation for more options that can be passed, but these will be enough for most of the applications.

prog — The program’s name.

description — A short description of your application.

epilog — An epilogue to be printed at the end of the help flag.

argument_default — The global default value for arguments.

add-help — Adds a help flag that prints the list of flags and commands that can be specified.

ArgumentParser Object.

Step 2: Add Arguments

To add arguments of flags you must use the add_argument method from the ArgumentParser object. This will allow you to specify commands and their respective actions that must be done when called. These are some of the common parameters you will want to specify when declaring a new argument.

name or flag — The first and most important parameter is the name of your command or flag. Choose something that is clear to understand and representative of the action that will be performed when called.

action — The type of action that will be performed when called. The most typical is store, this will store the argument’svalue.

nargs — Used to specify the number of arguments your command will handle. Works best when specifying a constant number of arguments, but if you need a more flexible approach for variable input, ‘*’ or ‘+’ can be used instead.

default — The default value of the argument.

choices — You can restrict the command line arguments that can be selected by specifying it with a list of accepted choices.

required — Specify whether or not an argument is required.

help — Text that will be printed to describe the argument when the help function is called.

add_argument Method.

Step 3: Parsing the Arguments

After you have defined all of your commands and flags, like the example above, you will have to parse these commands. This can be done in a single line:

Parsing the arguments

This will allow you to access the inputted arguments and then you can access that information to run functions or whatever action you want to perform. You can access this information by using args.’nameofcommand’, for example, using the argument we parsed in the previous step we could have something like this to run a different function depending on the inputted value for the command.

Handle command argument information.


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

User Popularity
24

Influence

2k

Total Hits

1

Posts

Mentioned tools