Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Building Command Line Interfaces With argparse
Command-line apps may not be common in the general user’s space, but they’re present in development, data science, systems administration, and many other operations. Every command-line app needs a user-friendly command-line interface (CLI) so that you can interact with the app itself. In Python, you can create full-featured CLIs with the argparse module from the standard library.
In this article, you’ll learn how to:
- Get started with command-line interfaces
- Organize and lay out a command-line app project in Python
- Create command-line interfaces with Python’s
argparse - Deeply customize your CLIs with some powerful features of
argparse
To get the most out of this tutorial, you should be familiar with Python programming, including concepts such as object-oriented programming, script development and execution, and Python packages and modules. It’ll also be helpful if you’re familiar with general concepts and topics related to using a command line or terminal.
Source Code: Click here to download the source code that you’ll use to build command-line interfaces with argparse.
Take the Quiz: Test your knowledge with our interactive “Build Command-Line Interfaces With Python's argparse” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Build Command-Line Interfaces With Python's argparseIn this quiz, you'll test your understanding of creating command-line interfaces (CLIs) in Python using the argparse module. This knowledge is essential for creating user-friendly command-line apps, which are common in development, data science, and systems administration.
Getting to Know Command-Line Interfaces
Since the invention of computers, humans have always needed and found ways to interact and share information with these machines. The information exchange has flowed among humans, computer software, and hardware components. The shared boundary between any two of these elements is generically known as an interface.
In software development, an interface is a special part of a given piece of software that allows interaction between components of a computer system. When it comes to human and software interaction, this vital component is known as the user interface.
You’ll find different types of user interfaces in programming. Probably, graphical user interfaces (GUIs) are the most common today. However, you’ll also find apps and programs that provide command-line interfaces (CLIs) for their users. In this tutorial, you’ll learn about CLIs and how to create them in Python.
Command-Line Interfaces (CLIs)
Command-line interfaces allow you to interact with an application or program through your operating system command line, terminal, or console.
To understand command-line interfaces and how they work, consider this practical example. Say that you have a directory called sample containing three sample files. If you’re on a Unix-like operating system, such as Linux or macOS, go ahead and open a command-line window or terminal in the parent directory and then execute the following command:
$ ls sample/
hello.txt lorem.md realpython.md
The ls Unix command lists the files and subdirectories contained in a target directory, which defaults to the current working directory. The above command call doesn’t display much information about the content of sample. It only displays the filenames on the screen.
Note: If you’re on Windows, then you’ll have an ls command that works similarly to the Unix ls command. However, in its plain form, the command displays a different output:
PS> ls .\sample\
Directory: C:\sample
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 11/10/2022 10:06 AM 88 hello.txt
-a--- 11/10/2022 10:06 AM 2629 lorem.md
-a--- 11/10/2022 10:06 AM 429 realpython.md
The PowerShell ls command issues a table containing detailed information on every file and subdirectory under your target directory. So, the upcoming examples won’t work as expected on Windows systems.
Suppose you want richer information about your directory and its content. In that case, you don’t need to look around for a program other than ls because this command has a full-featured command-line interface with a useful set of options that you can use to customize the command’s behavior.
For example, go ahead and execute ls with the -l option:
$ ls -l sample/
total 24
-rw-r--r--@ 1 user staff 83 Aug 17 22:15 hello.txt
-rw-r--r--@ 1 user staff 2609 Aug 17 22:15 lorem.md
-rw-r--r--@ 1 user staff 428 Aug 17 22:15 realpython.md
The output of ls is quite different now. The command displays much more information about the files in sample, including permissions, owner, group, date, and size. It also shows the total space that these files use on your computer’s disk.
Note: To get a detailed list of all the options that ls provides as part of its CLI, go ahead and run the man ls command in your command line or terminal.
This richer output results from using the -l option, which is part of the Unix ls command-line interface and enables the detailed output format.
Commands, Arguments, Options, Parameters, and Subcommands
Throughout this tutorial, you’ll learn about commands and subcommands. You’ll also learn about command-line arguments, options, and parameters, so you should incorporate these terms into your tech vocabulary:
-
Command: A program or routine that runs at the command line or terminal window. You’ll typically identify a command with the name of the underlying program or routine.
-
Argument: A required or optional piece of information that a command uses to perform its intended action. Commands typically accept one or many arguments, which you can provide as a whitespace-separated or comma-separated list on your command line.
-
Option, also known as flag or switch: An optional argument that modifies a command’s behavior. Options are passed to commands using a specific name, like
-lin the previous example. -
Parameter: An argument that an option uses to perform its intended operation or action.
-
Subcommand: A predefined name that can be passed to an application to run a specific action.
Consider the sample command construct from the previous section:
$ ls -l sample/
In this example, you’ve combined the following components of a CLI:
ls: The command’s name or the app’s name-l: An option, switch, or flag that enables detailed outputssample: An argument that provides additional information to the command’s execution
Now consider the following command construct, which showcases the CLI of Python’s package manager, known as pip:
$ pip install -r requirements.txt
This is a common pip command construct, which you’ve probably seen before. It allows you to install the requirements of a given Python project using a requirements.txt file. In this example, you’re using the following CLI components:
pip: The command’s nameinstall: The name of a subcommand ofpip-r: An option of theinstallsubcommandrequirements.txt: An argument, specifically a parameter of the-roption
Now you know what command-line interfaces are and what their main parts or components are. It’s time to learn how to create your own CLIs in Python.
Getting Started With CLIs in Python: sys.argv vs argparse
Python comes with a couple of tools that you can use to write command-line interfaces for your programs and apps. If you need to quickly create a minimal CLI for a small program, then you can use the argv attribute from the sys module. This attribute automatically stores the arguments that you pass to a given program at the command line.
Using sys.argv to Build a Minimal CLI
As an example of using argv to create a minimal CLI, say that you need to write a small program that lists all the files in a given directory, similar to what ls does. In this situation, you can write something like this: