Construct a Command-Line App with Python in 7 Straightforward Steps – KDnuggets


Picture by Creator

 

Constructing easy tasks is a good way to be taught Python and any programming language normally. You may be taught the syntax to jot down for loops, use built-in capabilities, learn recordsdata, and way more. Nevertheless it’s solely whenever you begin constructing one thing that you just really “learn”.

Following the “learning by building” method, let’s code a easy TO-DO checklist app that we are able to run on the command line. Alongside the best way we’ll discover ideas like parsing command-line arguments and dealing with recordsdata and file paths. We’ll as effectively revisit fundamentals like defining customized capabilities.

So let’s get began!

 

 

By coding alongside to this tutorial, you’ll be capable of construct a TO-DO checklist app you’ll be able to run on the command line. Okay, so what would you just like the app to do? 

Like TO-DO lists on paper, you want to have the ability to add duties, lookup all duties, and take away duties (yeah, strikethrough or mark them executed on paper) after you’ve accomplished them, sure? So we’ll construct an app that lets us do the next.

Add duties to the checklist:
 

Build a Command-Line App with Python in 7 Easy Steps
Picture by Creator

 

Get a listing of all duties on the checklist:

 

Build a Command-Line App with Python in 7 Easy Steps
Picture by Creator

 

And in addition take away a job (utilizing its index) after you’ve completed it:

 

Build a Command-Line App with Python in 7 Easy Steps
Picture by Creator

 

Now let’s begin coding!

 

 

First, create a listing to your undertaking. And contained in the undertaking listing, create a Python script file. This would be the fundamental file for our to-do checklist app. Let’s name it todo.py

You do not want any third-party libraries for this undertaking. So solely be sure to’re utilizing a current model of Python. This tutorial makes use of Python 3.11.

 

 

Within the todo.py file, begin by importing the required modules. For our easy to-do checklist app, we’ll want the next:

  • argparse for command-line argument parsing 
  • os for file operations

So let’s import them each:

import argparse
import os

 

 

Recall that we’ll use command-line flags so as to add, checklist, and take away duties. We are able to use each brief and lengthy choices for every argument. For our app, let’s use the next:

  • -a or --add so as to add duties
  • -l or --list to checklist all duties
  • -r or --remove to take away duties utilizing index

Right here’s the place we’ll use the argparse module to parse the arguments supplied on the command line. We outline the create_parser() perform that does the next:

  • Initializes an ArgumentParser object (let’s name it parser). 
  • Provides arguments for including, itemizing, and eradicating duties by calling the add_argument() technique on the parser object. 

When including arguments we add each the brief and lengthy choices in addition to the corresponding assist message. So right here’s the create_parser() perform:

def create_parser():
    parser = argparse.ArgumentParser(description="Command-line Todo List App")
    parser.add_argument("-a", "--add", metavar="", assist="Add a new task")
    parser.add_argument("-l", "--list", motion="store_true", assist="List all tasks")
    parser.add_argument("-r", "--remove", metavar="", assist="Remove a task by index")
    return parser

 

 

We now have to outline capabilities to carry out the next job administration operations:

  • Including a job
  • Itemizing all duties
  • Eradicating a job by its index

The next perform add_task interacts with a easy textual content file to handle gadgets on the TO-DO checklist. It opens the file within the ‘append’ mode and provides the duty to the top of the checklist:

def add_task(job):
    with open("tasks.txt", "a") as file:
    file.write(job + "n")

 

Discover how we’ve used the with assertion to handle the file. Doing so ensures that the file is closed after the operation—even when there’s an error—minimizing useful resource leaks. 

To be taught extra, learn the part on context managers for environment friendly useful resource dealing with in this tutorial on writing environment friendly Python code.

The list_tasks perform lists all of the duties by checking if the file exists. The file is created solely whenever you add the primary job. We first test if the file exists after which learn and print out the duties. If there are presently no duties, we get a useful message. :

def list_tasks():
    if os.path.exists("tasks.txt"):
        with open("tasks.txt", "r") as file:
            duties = file.readlines()
        	for index, job in enumerate(duties, begin=1):
                print(f"{index}. {task.strip()}")
    else:
        print("No tasks found.")

 

We additionally implement a remove_task perform to take away duties by index. Opening the file within the ‘write’ mode overwrites the prevailing file. So we take away the duty comparable to the index and write the up to date TO-DO checklist to the file:

def remove_task(index):
    if os.path.exists("tasks.txt"):
        with open("tasks.txt", "r") as file:
            duties = file.readlines()
        with open("tasks.txt", "w") as file:
            for i, job in enumerate(duties, begin=1):
                if i != index:
                    file.write(job)
        print("Task removed successfully.")
    else:
        print("No tasks found.")

 

 

We’ve arrange the parser to parse command-line arguments. And we’ve additionally outlined the capabilities to carry out the duties of including, itemizing, and eradicating duties. So what’s subsequent?

You most likely guessed it. We solely have to name the right perform primarily based on the command-line argument obtained. Let’s outline a fundamental() perform to parse the command-line arguments utilizing the ArgumentParser object we’ve created in step 3. 

Primarily based on the supplied arguments, name the suitable job administration capabilities. This may be executed utilizing a easy if-elif-else ladder like so:

def fundamental():
    parser = create_parser()
    args = parser.parse_args()

    if args.add:
        add_task(args.add)
    elif args.checklist:
        list_tasks()
    elif args.take away:
        remove_task(int(args.take away))
    else:
        parser.print_help()

if __name__ == "__main__":
    fundamental()

 

 

Now you can run the TO-DO checklist app from the command line. Use the brief choice h or the lengthy choice assistto get data on the utilization:

$ python3 todo.py --help
utilization: todo.py [-h] [-a] [-l] [-r]

Command-line Todo Checklist App

choices:
  -h, --help  	present this assist message and exit
  -a , --add  	Add a brand new job
  -l, --list  	Checklist all duties
  -r , --remove   Take away a job by index

 

Initially, there are not any duties within the checklist, so utilizing --list to checklist all duties print out “No tasks found.”:

$ python3 todo.py --list
No duties discovered.

 

Now we add an merchandise to the TO-DO checklist like so:

$ python3 todo.py -a "Walk 2 miles"

 

While you checklist the gadgets now,  you need to be capable of see the duty added:

$ python3 todo.py --list
1. Stroll 2 miles

 

As a result of we’ve added the primary merchandise the duties.txt file has been created (Consult with the definition of the list_tasks perform in step 4):

 

Let’s add one other job to the checklist:

$ python3 todo.py -a "Grab evening coffee!"

 

And one other:

$ python3 todo.py -a "Buy groceries"

 

And now let’s get the checklist of all duties:

$ python3 todo.py -l
1. Stroll 2 miles
2. Seize night espresso!
3. Purchase groceries

 

Now let’s take away a job by its index. Say we’re executed with night espresso (and hopefully for the day), so we take away it as proven:

$ python3 todo.py -r 2
Job eliminated efficiently.

 

The modified TO-DO checklist is as follows:

$ python3 todo.py --list
1. Stroll 2 miles
2. Purchase groceries

 

 

Okay, the only model of our app is prepared. So how will we take this additional? Right here are some things you’ll be able to strive:

  • What occurs whenever you use an invalid command-line choice (say -w or --wrong)? The default habits (when you recall from the if-elif-else ladder) is to print out the assistance message however there’ll be an exception, too. Attempt implementing error dealing with utilizing try-except blocks.
  • Check your app by defining check instances that embrace edge instances. To begin, you need to use the built-in unittest module.
  • Enhance the prevailing model by including an choice to specify the precedence for every job. Additionally attempt to kind and retrieve duties by precedence.

▶️ The code for this tutorial is on GitHub.

 

 

On this tutorial, we constructed a easy command-line TO-DO checklist app. In doing so, we discovered the right way to use the built-in argparse module to parse command-line arguments. We additionally used the command-line inputs to carry out corresponding operations on a easy textual content file beneath the hood. 

So the place will we go subsequent? Properly, Python libraries like Typer make constructing command-line apps a breeze. And we’ll construct one utilizing Typer in an upcoming Python tutorial. Till then, maintain coding!
 
 

Bala Priya C is a developer and technical author from India. She likes working on the intersection of math, programming, knowledge science, and content material creation. Her areas of curiosity and experience embrace DevOps, knowledge science, and pure language processing. She enjoys studying, writing, coding, and low! At present, she’s engaged on studying and sharing her data with the developer group by authoring tutorials, how-to guides, opinion items, and extra. Bala additionally creates partaking useful resource overviews and coding tutorials.

Recent articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here