This article discusses how you can create a CLI for your python programs using an example in which we make a basic “text file manager”.
Let us discuss some basics first.
What is a Command Line Interface(CLI)?
A command-line interface or command language interpreter (CLI), also known as command-line user interface, console user interface, and character user interface (CUI), is a means of interacting with a computer program where the user (or client) issues commands to the program in the form of successive lines of text (command lines).(Wiki)
Advantages of CLI:
- Requires fewer resources
- Concise and powerful
- Easier to automate via scripting
Why to use CLI in your python program?
- Having even just a very basic command-line interface (CLI) for your program can make everyone’s life easier for modifying parameters, including programmers, but also non-programmers.
- A CLI for your program can also make it easier to automate running and modifying variables within your program, for when you want to run your program with a cronjob or maybe an os.system call.
Now, let us start making our “Text file manager”. Here, we will be using a built-in python library called Argparse.
- It 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.
Ok let’s start with a really basic program to get a feel of what argparse does.
Let us go through some important points related to above program:
- First of all, we imported the argparse module.
- Then, created a ArgumentParser object and also provided a description of our program.
- Now, we can fill up our parser object with information by adding arguments. In this example, we created an argument add. A lot of arguments can be passed to the add_argument function. Here I explain the ones I have used in above example:
argument 1: (“add”) It is nothing but the name of the argument. We will use this name to access the add arguments by typing args.add.
argument 2: (nargs = ‘*’) The number of command-line arguments that should be consumed. Specifying it to ‘*’ means it can be any no. of arguments i.e, from 0 to anything.
argument 3: (metavar = ‘num’) A name for the argument in usage messages.
argument 4: (type = int) The type to which the command-line argument should be converted. It is str by default.
argument 5: (help) A brief description of what the argument does.
- Once we have specified all the arguments, it is the time to parse the arguments from the standard command line input stream. For this, we use parse_args() function.
- Now, one can simply check if the input has invoked a specific argument. Here, we check the length of args.add to check if there is any data received from input. Note that values of an argument are obtained as a list.
- There are two types of arguments: Positional and Optional.
Positional ones are those which do not need any specification to be invoked. Whereas, optional arguments need to be specified by their name first (which starts with ‘–‘ sign, ‘-‘ is also a shorthand.)
- One can always use –help or -h optional argument to see the help message.
Here is an example (The python script has been saved as add.py):
- Now, let us have a look at another example where our positional argument add is invoked.
- One more special feature worth mentioning is how argparse issues errors when users give the program invalid arguments.
So, this was a basic example so that you can get comfortable with argparse and CLI concept. Now, let us move on to our “Text file manager” program.
After the previous example, the above code seems self explanatory.
All we did was to add a set of arguments for our file manager program. Note that all these arguments are optional arguments. So, we use some if-elif statements to match the command line input with correct argument type function so that query could be processed.
Here are a few screenshots which describe the usage of above program:
- Help message (The python script has been saved as tfmanager.py):
- Here are examples of operations using the text file manager:
So, this was an example of a simple CLI python program which we made. Many complex CLIs could be easily created by the Argparse module. I hope that these examples will give you a head start in this area.
This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- How to write an empty function in Python - pass statement?
- Operator Functions in Python | Set 2
- Time Functions in Python | Set-2 (Date Manipulations)
- Send mail from your Gmail account using Python
- Python – The new generation Language
- Print Single and Multiple variable in Python
- Increment and Decrement Operators in Python
- str() vs repr() in Python
- Swap two variables in one line in C/C++, Python, PHP and Java
- Generate all permutation of a set in Python
- Class or Static Variables in Python
- trunc() in Python
- Division Operators in Python
- Interesting facts about strings in Python | Set 1
- When to use yield instead of return in Python?