Command-line arguments allow you to interact with programs and modify their output. And they are not any less important in Python. In my tutorial, How to Build a Keyboard Sound Simulator in Python for Linux, you knew that we can add some features to the program to improve it. So, here is how to use Argparse for parsing command-line arguments and options in Python.
As of Python >= 2.7 and >= 3.2, the
argparse module is maintained within the Python standard library, which means you don’t have to do anything to install it. But if, for some reason, you need to support Python < 2.7 or < 3.2, you can very easily install it via
pip install argparse.
First of all, you need to define/add arguments, so that
argparse can parse them for you. Take a look at this, almost familiar to every programmer,
$ ls -a
You can see that
ls is the name of the command and
-a is an argument that tells the command to list all files. It is also identical to
argparse, here is how to define an argument.
import argparse. Then, we define the
parser as shown on line 3. We will talk about that
description argument in a minute. Afterward, we add the arguments we want as shown on line 6. As you may have guessed, the first argument to the
'-v', is the short form of the argument. And the second one,
'--volume', is the long-form. And obviously
type indicates the type of variable you are expecting and
default is the default value if no value is passed. We will talk about
help later. After that, we actually parse the arguments as shown on line 9. Finally, we can use them, as shown on line 11, by using
Displaying a Help Message
At this point, if you put those lines in a file called
file.py and run it like this:
python file.py -h, you would get this help message.
As you can see,
argparse has automatically generated this help message and added the
-h/--help argument for us. The string we passed as
description when creating the
argument parser is shown on line 3. And that we passed as
help when creating the
-v/--volume argument is shown on line 8.
There are many ways to parse command-line arguments passed to a Python program, and using
argparse is probably the easiest of them all. So, now you can now define and parse command-line arguments in Python, and also add a nice helpful help message to your program.
NOTE: The source code for this article can be found here.