Sure! Below is a Python script that fulfills the requirements you've specified for the task tracker CLI application. The script uses only standard libraries and adheres to the constraints you've mentioned.
#!/usr/bin/env python3
import os
import json
import argparse
from datetime import datetime
# File name for storing tasks
TASKS_FILE = 'tasks.json'
def load_tasks():
"""Load tasks from the JSON file."""
if not os.path.exists(TASKS_FILE):
return []
with open(TASKS_FILE, 'r') as f:
try:
tasks = json.load(f)
except json.JSONDecodeError:
tasks = []
return tasks
def save_tasks(tasks):
"""Save tasks to the JSON file."""
with open(TASKS_FILE, 'w') as f:
json.dump(tasks, f, indent=4)
def add_task(description):
"""Add a new task."""
tasks = load_tasks()
task_id = 1
if tasks:
task_id = max(task['id'] for task in tasks) + 1
now = datetime.now().isoformat()
task = {
'id': task_id,
'description': description,
'status': 'todo',
'createdAt': now,
'updatedAt': now
}
tasks.append(task)
save_tasks(tasks)
print(f'Task added successfully (ID: {task_id})')
def update_task(task_id, new_description):
"""Update an existing task."""
tasks = load_tasks()
for task in tasks:
if task['id'] == task_id:
task['description'] = new_description
task['updatedAt'] = datetime.now().isoformat()
save_tasks(tasks)
print('Task updated successfully')
return
print(f'Error: Task with ID {task_id} not found')
def delete_task(task_id):
"""Delete a task."""
tasks = load_tasks()
for idx, task in enumerate(tasks):
if task['id'] == task_id:
del tasks[idx]
save_tasks(tasks)
print('Task deleted successfully')
return
print(f'Error: Task with ID {task_id} not found')
def mark_in_progress(task_id):
"""Mark a task as in progress."""
tasks = load_tasks()
for task in tasks:
if task['id'] == task_id:
task['status'] = 'in-progress'
task['updatedAt'] = datetime.now().isoformat()
save_tasks(tasks)
print('Task marked as in progress')
return
print(f'Error: Task with ID {task_id} not found')
def mark_done(task_id):
"""Mark a task as done."""
tasks = load_tasks()
for task in tasks:
if task['id'] == task_id:
task['status'] = 'done'
task['updatedAt'] = datetime.now().isoformat()
save_tasks(tasks)
print('Task marked as done')
return
print(f'Error: Task with ID {task_id} not found')
def list_tasks(status=None):
"""List tasks, optionally filtering by status."""
tasks = load_tasks()
if status:
tasks = [task for task in tasks if task['status'] == status]
if not tasks:
print('No tasks found')
return
for task in tasks:
print(f"ID: {task['id']}, Description: {task['description']}, Status: {task['status']}")
def main():
parser = argparse.ArgumentParser(description='Task Tracker CLI')
subparsers = parser.add_subparsers(dest='command', required=True)
# Add command
parser_add = subparsers.add_parser('add', help='Add a new task')
parser_add.add_argument('description', type=str, help='Description of the task')
# Update command
parser_update = subparsers.add_parser('update', help='Update an existing task')
parser_update.add_argument('id', type=int, help='ID of the task to update')
parser_update.add_argument('description', type=str, help='New description of the task')
# Delete command
parser_delete = subparsers.add_parser('delete', help='Delete a task')
parser_delete.add_argument('id', type=int, help='ID of the task to delete')
# Mark in progress command
parser_mark_in_progress = subparsers.add_parser('mark-in-progress', help='Mark a task as in progress')
parser_mark_in_progress.add_argument('id', type=int, help='ID of the task')
# Mark done command
parser_mark_done = subparsers.add_parser('mark-done', help='Mark a task as done')
parser_mark_done.add_argument('id', type=int, help='ID of the task')
# List command
parser_list = subparsers.add_parser('list', help='List tasks')
parser_list.add_argument('status', nargs='?', choices=['todo', 'in-progress', 'done'], help='Filter tasks by status')
args = parser.parse_args()
if args.command == 'add':
add_task(args.description)
elif args.command == 'update':
update_task(args.id, args.description)
elif args.command == 'delete':
delete_task(args.id)
elif args.command == 'mark-in-progress':
mark_in_progress(args.id)
elif args.command == 'mark-done':
mark_done(args.id)
elif args.command == 'list':
list_tasks(args.status)
if __name__ == '__main__':
main()
How to Use the Script
-
Save the script as task-cli.py in the directory where you want to manage your tasks.
-
Make the script executable (optional):
chmod +x task-cli.py
-
Run the script using the command line with the specified commands:
Adding a New Task
./task-cli.py add "Buy groceries"
Output:
Task added successfully (ID: 1)
Updating a Task
./task-cli.py update 1 "Buy groceries and cook dinner"
Output:
Task updated successfully
Deleting a Task
./task-cli.py delete 1
Output:
Task deleted successfully
Marking a Task as In Progress
./task-cli.py mark-in-progress 1
Output:
Task marked as in progress
Marking a Task as Done
./task-cli.py mark-done 1
Output:
Task marked as done
Listing All Tasks
./task-cli.py list
Output:
ID: 1, Description: Buy groceries, Status: todo
ID: 2, Description: Finish report, Status: in-progress
Listing Tasks by Status
Task Properties
Each task in tasks.json has the following properties:
- id: A unique integer identifier for the task.
- description: A short description of the task.
- status: The status of the task (
todo, in-progress, done).
- createdAt: The ISO timestamp when the task was created.
- updatedAt: The ISO timestamp when the task was last updated.
Example entry in tasks.json:
{
"id": 1,
"description": "Buy groceries",
"status": "todo",
"createdAt": "2023-10-05T14:48:00.000000",
"updatedAt": "2023-10-05T14:48:00.000000"
}
Notes and Constraints Handling
- No External Libraries: The script uses only Python's standard library modules (
os, json, argparse, datetime).
- Positional Arguments: Command-line arguments are positional and parsed using
argparse.
- JSON File Handling: The script checks if
tasks.json exists and creates it if it does not. It also handles potential JSON decoding errors.
- Error Handling: The script provides meaningful error messages if, for example, a task ID is not found.
- Edge Cases: The script handles edge cases such as attempting to list tasks when none exist.
Running the Script Without Making it Executable
If you do not make the script executable, you can run it using:
python3 task-cli.py [command] [arguments]
Final Remarks
This script provides a simple yet functional task management system right from the command line. It should serve as a good starting point for practicing CLI application development and can be extended with additional features as needed.
Feel free to ask if you have any questions or need further assistance!