Picture by Creator
Constructing easy tasks is an effective way to be taught Python and any programming language normally. You may be taught the syntax to put in writing for loops, use built-in capabilities, learn information, and rather more. But it surely’s solely once you begin constructing one thing that you just truly “be taught”.
Following the “studying by constructing” method, let’s code a easy TO-DO record app that we are able to run on the command line. Alongside the way in which we’ll discover ideas like parsing command-line arguments and dealing with information and file paths. We’ll as properly revisit fundamentals like defining customized capabilities.
So let’s get began!
By coding alongside to this tutorial, you’ll be capable to construct a TO-DO record app you may 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, search for all duties, and take away duties (yeah, strikethrough or mark them completed on paper) after you’ve accomplished them, sure? So we’ll construct an app that lets us do the next.
Add duties to the record:
Picture by Creator
Get a listing of all duties on the record:
Picture by Creator
And likewise take away a job (utilizing its index) after you’ve completed it:
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 most important file for our to-do record 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 latest 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 record app, we’ll want the next:
So let’s import them each:
import argparse
import os
Recall that we’ll use command-line flags so as to add, record, and take away duties. We will 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 record 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 offered on the command line. We outline the create_parser()
operate that does the next:
- Initializes an
ArgumentParser
object (let’s name itparser
). - Provides arguments for including, itemizing, and eradicating duties by calling the
add_argument()
methodology 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()
operate:
def create_parser():
parser = argparse.ArgumentParser(description="Command-line Todo Listing App")
parser.add_argument("-a", "--add", metavar="", assist="Add a brand new job")
parser.add_argument("-l", "--list", motion="store_true", assist="Listing all duties")
parser.add_argument("-r", "--remove", metavar="", assist="Take away a job by index")
return parser
We now must outline capabilities to carry out the next job administration operations:
- Including a job
- Itemizing all duties
- Eradicating a job by its index
The next operate add_task
interacts with a easy textual content file to handle gadgets on the TO-DO record. It opens the file within the ‘append’ mode and provides the duty to the top of the record:
def add_task(job):
with open("duties.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
operate lists all of the duties by checking if the file exists. The file is created solely once you add the primary job. We first verify 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("duties.txt"):
with open("duties.txt", "r") as file:
duties = file.readlines()
for index, job in enumerate(duties, begin=1):
print(f"{index}. {job.strip()}")
else:
print("No duties discovered.")
We additionally implement a remove_task
operate to take away duties by index. Opening the file within the ‘write’ mode overwrites the present file. So we take away the duty equivalent to the index and write the up to date TO-DO record to the file:
def remove_task(index):
if os.path.exists("duties.txt"):
with open("duties.txt", "r") as file:
duties = file.readlines()
with open("duties.txt", "w") as file:
for i, job in enumerate(duties, begin=1):
if i != index:
file.write(job)
print("Job eliminated efficiently.")
else:
print("No duties discovered.")
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 must name the right operate based mostly on the command-line argument obtained. Let’s outline a most important()
operate to parse the command-line arguments utilizing the ArgumentParser
object we’ve created in step 3.
Based mostly on the offered arguments, name the suitable job administration capabilities. This may be completed utilizing a easy if-elif-else ladder like so:
def most important():
parser = create_parser()
args = parser.parse_args()
if args.add:
add_task(args.add)
elif args.record:
list_tasks()
elif args.take away:
remove_task(int(args.take away))
else:
parser.print_help()
if __name__ == "__main__":
most important()
Now you can run the TO-DO record app from the command line. Use the brief choice h
or the lengthy choice assist
to get info on the utilization:
$ python3 todo.py --help
utilization: todo.py [-h] [-a] [-l] [-r]
Command-line Todo Listing App
choices:
-h, --help present this assist message and exit
-a , --add Add a brand new job
-l, --list Listing all duties
-r , --remove Take away a job by index
Initially, there aren’t any duties within the record, so utilizing --list
to record all duties print out “No duties discovered.”:
$ python3 todo.py --list
No duties discovered.
Now we add an merchandise to the TO-DO record like so:
$ python3 todo.py -a "Stroll 2 miles"
While you record the gadgets now, you need to be capable to 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 (Check with the definition of the list_tasks
operate in step 4):
Let’s add one other job to the record:
$ python3 todo.py -a "Seize night espresso!"
And one other:
$ python3 todo.py -a "Purchase groceries"
And now let’s get the record 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 completed 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 record is as follows:
$ python3 todo.py --list
1. Stroll 2 miles
2. Purchase groceries
Okay, the best model of our app is prepared. So how can we take this additional? Right here are some things you may strive:
- What occurs once you use an invalid command-line choice (say
-w
or--wrong
)? The default habits (for those who 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. - Take a look at your app by defining check circumstances that embody edge circumstances. To start out, you should utilize the built-in unittest module.
- Enhance the present model by including an choice to specify the precedence for every job. Additionally attempt to type and retrieve duties by precedence.
▶️ The code for this tutorial is on GitHub.
On this tutorial, we constructed a easy command-line TO-DO record app. In doing so, we realized find out how 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 can we go subsequent? Effectively, 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, preserve 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 embody DevOps, knowledge science, and pure language processing. She enjoys studying, writing, coding, and low! At the moment, she’s engaged on studying and sharing her information with the developer neighborhood by authoring tutorials, how-to guides, opinion items, and extra. Bala additionally creates partaking useful resource overviews and coding tutorials.