DEV Community

Cover image for Manage your tasks with the terminal
Stokry
Stokry

Posted on

Manage your tasks with the terminal

In today’s fast-paced world, staying organized and managing tasks effectively is more critical than ever. Whether you’re a developer, a student, or a professional juggling multiple projects, having a reliable task management system can make a world of difference. But what if you could create your own customized task manager with just a bit of Python and SQLite?

Manage your tasks with the terminal :-)

We’re excited to share a Python script that not only helps you add, update, and display tasks but also allows you to delete all tasks with a simple command. Brefaly here’s what script does:

Create a Task Table: It automatically sets up your SQLite database with the necessary table and columns.

Add Tasks: It allows you to effortlessly add new tasks, with optional due dates.

Update Task Status: It enables you to easily update the status of your tasks to monitor your progress.

Delete All Tasks: It clears all tasks with a confirmation prompt to ensure you don't delete them unintentionally.

Display Tasks: It lets you view all your tasks in a clean, tabular format

Setting Up the Table

The script begins by creating a table in your SQLite database if it doesn't already exist. It even checks for a due_date column and adds it if it's absent:

def create_table(conn):
    sql_create_tasks_table = """ CREATE TABLE IF NOT EXISTS tasks (
                                    id integer PRIMARY KEY,
                                    task text NOT NULL,
                                    status text NOT NULL
                                ); """
    c = conn.cursor()
    c.execute(sql_create_tasks_table)

    # Check if due_date column exists, if not, add it
    c.execute("PRAGMA table_info(tasks)")
    columns = [column[1] for column in c.fetchall()]
    if 'due_date' not in columns:
        c.execute("ALTER TABLE tasks ADD COLUMN due_date text")
    conn.commit()
Enter fullscreen mode Exit fullscreen mode

Adding New Tasks

Adding a task is as simple as calling the add_task function. You can even set a due date:

def add_task(conn, task, due_date=None):
    sql = ''' INSERT INTO tasks(task, status, due_date)
              VALUES(?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, (task, 'Pending', due_date))
    conn.commit()
    return cur.lastrowid
Enter fullscreen mode Exit fullscreen mode

Updating Task Status

Need to mark a task as completed? Just update its status:

def update_task(conn, task_id, status):
    sql = ''' UPDATE tasks
              SET status = ?
              WHERE id = ?'''
    cur = conn.cursor()
    cur.execute(sql, (status, task_id))
    conn.commit()
Enter fullscreen mode Exit fullscreen mode

Deleting All Tasks

Want a fresh start? You can delete all tasks with a simple command, but don’t worry – it asks for confirmation first:

def delete_all_tasks(conn):
    sql = 'DELETE FROM tasks'
    cur = conn.cursor()
    cur.execute(sql)
    conn.commit()
Enter fullscreen mode Exit fullscreen mode

Displaying Tasks

See all your tasks neatly listed in the console:

def display_tasks(conn):
    tasks = select_all_tasks(conn)
    print("\nAll Tasks:")
    print("-" * 50)
    print("ID | Task | Status | Due Date")
    print("-" * 50)
    for task in tasks:
        due_date = task[3] if len(task) > 3 and task[3] else "Not set"
        print(f"{task[0]} | {task[1]} | {task[2]} | {due_date}")
    print("-" * 50)
Enter fullscreen mode Exit fullscreen mode

User-Friendly Menu

The script includes a user-friendly menu to interact with your task manager:

def menu():
    print("\n1. Add Task")
    print("2. Update Task Status")
    print("3. Delete All Tasks")
    print("4. Exit")
Enter fullscreen mode Exit fullscreen mode

Bringing It All Together

Here’s the main function that ties everything together, providing a seamless user experience:

def main():
    database = "todo.db"
    conn = sqlite3.connect(database)
    if conn is not None:
        create_table(conn)
    else:
        print("Error! Cannot create the database connection.")
        return

    while True:
        display_tasks(conn)
        menu()
        choice = input("Enter choice: ")
        if choice == '1':
            task = input("Enter task: ")
            due_date = input("Enter due date (YYYY-MM-DD) or press Enter to skip: ")
            due_date = due_date if due_date else None
            add_task(conn, task, due_date)
        elif choice == '2':
            task_id = int(input("Enter task ID to update: "))
            status = input("Enter new status (Pending/Completed): ")
            update_task(conn, task_id, status)
        elif choice == '3':
            confirmation = input("Are you sure you want to delete all tasks? (yes/no): ")
            if confirmation.lower() == 'yes':
                delete_all_tasks(conn)
                print("All tasks have been deleted.")
        elif choice == '4':
            conn.close()
            break
        else:
            print("Invalid choice! Please try again.")
Enter fullscreen mode Exit fullscreen mode

You can extend this script

Customizable: Adjust the script to meet your specific task management requirements.

Educational: Discover how to engage with SQLite databases using Python.

Efficient: Handle tasks straight from your terminal, eliminating the need for third-party apps.

enter image description here

This script empowers you to manage your tasks efficiently and effectively. Happy coding!

Top comments (0)