In this step, we'll combine everything we've learned to build a complete command-line tool. Let's create a simple task manager that allows users to add, list, and delete tasks using command-line arguments.
Creating the Task Manager
- Create a new file named
task_manager.py
in the /home/labex/project
directory
- Add the following code:
import argparse
import json
import os
## File to store tasks
TASKS_FILE = "/home/labex/project/tasks.json"
def load_tasks():
"""Load tasks from the JSON file."""
if os.path.exists(TASKS_FILE):
with open(TASKS_FILE, 'r') as f:
try:
return json.load(f)
except json.JSONDecodeError:
return []
return []
def save_tasks(tasks):
"""Save tasks to the JSON file."""
with open(TASKS_FILE, 'w') as f:
json.dump(tasks, f, indent=2)
def main():
## Create the main parser
parser = argparse.ArgumentParser(description='Task Manager CLI')
subparsers = parser.add_subparsers(dest='command', help='Command to run')
## Add command
add_parser = subparsers.add_parser('add', help='Add a new task')
add_parser.add_argument('title', help='Task title')
add_parser.add_argument('-p', '--priority',
choices=['low', 'medium', 'high'],
default='medium',
help='Task priority (default: medium)')
add_parser.add_argument('-d', '--due',
help='Due date (format: YYYY-MM-DD)')
## List command
list_parser = subparsers.add_parser('list', help='List all tasks')
list_parser.add_argument('-p', '--priority',
choices=['low', 'medium', 'high'],
help='Filter tasks by priority')
list_parser.add_argument('-s', '--sort',
choices=['priority', 'title'],
default='priority',
help='Sort tasks by criteria (default: priority)')
## Delete command
delete_parser = subparsers.add_parser('delete', help='Delete a task')
delete_parser.add_argument('task_id', type=int, help='Task ID to delete')
## Parse arguments
args = parser.parse_args()
## Load existing tasks
tasks = load_tasks()
## Handle commands
if args.command == 'add':
## Add a new task
new_task = {
'id': len(tasks) + 1,
'title': args.title,
'priority': args.priority,
'due': args.due
}
tasks.append(new_task)
save_tasks(tasks)
print(f"Task added: {new_task['title']} (ID: {new_task['id']})")
elif args.command == 'list':
## List tasks
if not tasks:
print("No tasks found.")
return
## Filter by priority if specified
if args.priority:
filtered_tasks = [t for t in tasks if t['priority'] == args.priority]
else:
filtered_tasks = tasks
## Sort tasks
if args.sort == 'priority':
## Custom priority sorting
priority_order = {'high': 0, 'medium': 1, 'low': 2}
sorted_tasks = sorted(filtered_tasks, key=lambda x: priority_order[x['priority']])
else:
## Sort by title
sorted_tasks = sorted(filtered_tasks, key=lambda x: x['title'])
## Display tasks
print("ID | Title | Priority | Due Date")
print("-" * 50)
for task in sorted_tasks:
due_date = task['due'] if task['due'] else 'N/A'
print(f"{task['id']:2} | {task['title'][:20]:<20} | {task['priority']:<8} | {due_date}")
elif args.command == 'delete':
## Delete a task
task_id = args.task_id
task_found = False
for i, task in enumerate(tasks):
if task['id'] == task_id:
del tasks[i]
task_found = True
break
if task_found:
save_tasks(tasks)
print(f"Task {task_id} deleted.")
else:
print(f"Task {task_id} not found.")
else:
## No command specified
parser.print_help()
if __name__ == "__main__":
main()
Understanding the Task Manager
This script demonstrates several advanced features of argparse:
- Subparsers - Creating command-specific argument sets
- Command-specific arguments - Different arguments for add, list, and delete commands
- Nested validation - Priority choices limited to specific values
- Default values - Providing sensible defaults for optional arguments
Testing the Task Manager
Let's run the script with different commands to see how it works:
- Adding tasks:
python3 task_manager.py add "Complete Python tutorial" -p high -d 2023-12-31
Output:
Task added: Complete Python tutorial (ID: 1)
Add a few more tasks:
python3 task_manager.py add "Read documentation" -p medium
python3 task_manager.py add "Take a break" -p low -d 2023-12-25
- Listing tasks:
python3 task_manager.py list
Output:
ID | Title | Priority | Due Date
--------------------------------------------------
1 | Complete Python tutor | high | 2023-12-31
2 | Read documentation | medium | N/A
3 | Take a break | low | 2023-12-25
- Listing tasks with filtering and sorting:
python3 task_manager.py list -s title
Output:
ID | Title | Priority | Due Date
--------------------------------------------------
1 | Complete Python tutor | high | 2023-12-31
2 | Read documentation | medium | N/A
3 | Take a break | low | 2023-12-25
- Filtering by priority:
python3 task_manager.py list -p high
Output:
ID | Title | Priority | Due Date
--------------------------------------------------
1 | Complete Python tutor | high | 2023-12-31
- Deleting a task:
python3 task_manager.py delete 2
Output:
Task 2 deleted.
Verify the task was deleted:
python3 task_manager.py list
Output:
ID | Title | Priority | Due Date
--------------------------------------------------
1 | Complete Python tutor | high | 2023-12-31
3 | Take a break | low | 2023-12-25
Getting Help for Subcommands
Argparse automatically generates help for each subcommand:
python3 task_manager.py add --help
Output:
usage: task_manager.py add [-h] [-p {low,medium,high}] [-d DUE] title
positional arguments:
title Task title
options:
-h, --help show this help message and exit
-p {low,medium,high}, --priority {low,medium,high}
Task priority (default: medium)
-d DUE, --due DUE Due date (format: YYYY-MM-DD)
Key Points About Subparsers
- Subparsers create command-specific argument sets
- Each subparser can have its own arguments
- The
dest
parameter specifies where the command name will be stored
- Help messages are automatically generated for each subcommand
- You can mix positional and optional arguments in subparsers
You now have a fully functional command-line tool that demonstrates the power and flexibility of argparse for handling complex argument scenarios.