如何使用Python制作 Todo List CLI 应用程序?
在本文中,我们将看到如何在Python制作命令行应用程序待办事项列表。待办事项列表是一个基本的应用程序,用户可以在其中添加项目。它是您需要完成的任务或想要做的事情的列表。在待办事项中,列表任务按优先级顺序排列。您应该使用待办事项列表的最重要原因之一是它可以帮助您保持井井有条。
在本文中,我们使用命令行制作待办事项列表。通过将待办事项列表用作命令行应用程序,我们可以通过命令提示符组织待办事项列表,而无需显式运行任何脚本或程序。
待办事项列表的基本功能是:
- 添加新的待办事项
- 删除待办事项
- 完成一个待办事项
- 显示剩余的待办事项
- 显示待办事项的统计信息
注意:在 Windows 命令提示符中运行应用程序 → 输入 todo 或.\todo
In shell or git bash --> type ./todo
- 要创建待办事项列表应用程序,我们必须遵循以下步骤:
- 创建一个名为 todolist 的文件夹
- 在创建的文件夹中创建一个文件 todo.py
- 如果您是寡妇用户,则创建另一个文件 todo.bat 文件。这是一个批处理文件。它用于运行Python脚本
- 如果您是 Linux 用户,则创建一个名为 todo.sh 的文件。这用于运行Python脚本。
待办事项.bat:
@echo off
python3 todo.py %1 %2
todo.sh:
python todo.py "$@"
创建指向可执行文件的符号链接:
在 Windows 中(在命令提示符或 Powershell 中)
要在 Windows 上创建符号链接,您需要以管理员权限**运行 Windows 命令提示符或 Windows Powershell。为此,请右键单击命令提示符或 Powershell 的图标,然后选择 _“以管理员身份运行”_ 选项。
mklink todo todo.bat
在 Linux 或 shell 中(如 git bash)
$ ln -s todo.sh todo
现在我们必须编写待办事项列表的功能。
所以我们在todo.py中编写代码
Python3
# module required
import sys
import datetime
Python3
# help function
def help():
sa = """Usage :-
$ ./todo add "todo item" # Add a new todo
$ ./todo ls # Show remaining todos
$ ./todo del NUMBER # Delete a todo
$ ./todo done NUMBER # Complete a todo
$ ./todo help # Show usage
$ ./todo report # Statistics"""
sys.stdout.buffer.write(sa.encode('utf8'))
Python3
# function to add item in todo list
def add(s):
f = open('todo.txt', 'a')
f.write(s)
f.write("\n")
f.close()
s = '"'+s+'"'
print(f"Added todo: {s}")
Python3
# Function to print the todo list items
def ls():
try:
nec()
l = len(d)
k = l
for i in d:
sys.stdout.buffer.write(f"[{l}] {d[l]}".encode('utf8'))
sys.stdout.buffer.write("\n".encode('utf8'))
l = l-1
except Exception as e:
raise e
Python3
# Function to Complete a todo
def done(no):
try:
nec()
no = int(no)
f = open('done.txt', 'a')
st = 'x '+str(datetime.datetime.today()).split()[0]+' '+d[no]
f.write(st)
f.write("\n")
f.close()
print(f"Marked todo #{no} as done.")
with open("todo.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for i in lines:
if i.strip('\n') != d[no]:
f.write(i)
f.truncate()
except:
print(f"Error: todo #{no} does not exist.")
Python3
# Function to show report/statistics of todo list
def report():
nec()
try:
nf = open('done.txt', 'r')
c = 1
for line in nf:
line = line.strip('\n')
don.update({c: line})
c = c+1
print(
f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}')
except:
print(
f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}')
Python3
# code
def deL(no):
try:
no = int(no)
nec()
# utility function defined in main
with open("todo.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for i in lines:
if i.strip('\n') != d[no]:
f.write(i)
f.truncate()
print(f"Deleted todo #{no}")
except Exception as e:
print(f"Error: todo #{no} does not exist. Nothing deleted.")
Python3
# code
def nec():
# utility function used in done and report function
try:
f = open('todo.txt', 'r')
c = 1
for line in f:
line = line.strip('\n')
d.update({c: line})
c = c+1
except:
sys.stdout.buffer.write("There are no pending todos!".encode('utf8'))
# Main program
if __name__ == '__main__':
try:
d = {}
don = {}
args = sys.argv
if(args[1] == 'del'):
args[1] = 'deL'
if(args[1] == 'add' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing todo string. Nothing added!".encode('utf8'))
elif(args[1] == 'done' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing NUMBER for marking todo as done.".encode('utf8'))
elif(args[1] == 'deL' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing NUMBER for deleting todo.".encode('utf8'))
else:
globals()[args[1]](*args[2:])
except Exception as e:
s = """Usage :-
$ ./todo add "todo item" # Add a new todo
$ ./todo ls # Show remaining todos
$ ./todo del NUMBER # Delete a todo
$ ./todo done NUMBER # Complete a todo
$ ./todo help # Show usage
$ ./todo report # Statistics"""
sys.stdout.buffer.write(s.encode('utf8'))
Python3
# Complete code
import sys
import datetime
def help():
sa = """Usage :-
$ ./todo add "todo item" # Add a new todo
$ ./todo ls # Show remaining todos
$ ./todo del NUMBER # Delete a todo
$ ./todo done NUMBER # Complete a todo
$ ./todo help # Show usage
$ ./todo report # Statistics"""
sys.stdout.buffer.write(sa.encode('utf8'))
def add(s):
f = open('todo.txt', 'a')
f.write(s)
f.write("\n")
f.close()
s = '"'+s+'"'
print(f"Added todo: {s}")
def ls():
try:
nec()
l = len(d)
k = l
for i in d:
sys.stdout.buffer.write(f"[{l}] {d[l]}".encode('utf8'))
sys.stdout.buffer.write("\n".encode('utf8'))
l = l-1
except Exception as e:
raise e
def deL(no):
try:
no = int(no)
nec()
with open("todo.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for i in lines:
if i.strip('\n') != d[no]:
f.write(i)
f.truncate()
print(f"Deleted todo #{no}")
except Exception as e:
print(f"Error: todo #{no} does not exist. Nothing deleted.")
def done(no):
try:
nec()
no = int(no)
f = open('done.txt', 'a')
st = 'x '+str(datetime.datetime.today()).split()[0]+' '+d[no]
f.write(st)
f.write("\n")
f.close()
print(f"Marked todo #{no} as done.")
with open("todo.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for i in lines:
if i.strip('\n') != d[no]:
f.write(i)
f.truncate()
except:
print(f"Error: todo #{no} does not exist.")
def report():
nec()
try:
nf = open('done.txt', 'r')
c = 1
for line in nf:
line = line.strip('\n')
don.update({c: line})
c = c+1
print(
f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}')
except:
print(
f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}')
def nec():
try:
f = open('todo.txt', 'r')
c = 1
for line in f:
line = line.strip('\n')
d.update({c: line})
c = c+1
except:
sys.stdout.buffer.write("There are no pending todos!".encode('utf8'))
if __name__ == '__main__':
try:
d = {}
don = {}
args = sys.argv
if(args[1] == 'del'):
args[1] = 'deL'
if(args[1] == 'add' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing todo string. Nothing added!".encode('utf8'))
elif(args[1] == 'done' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing NUMBER for marking todo as done.".encode('utf8'))
elif(args[1] == 'deL' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing NUMBER for deleting todo.".encode('utf8'))
else:
globals()[args[1]](*args[2:])
except Exception as e:
s = """Usage :-
$ ./todo add "todo item" # Add a new todo
$ ./todo ls # Show remaining todos
$ ./todo del NUMBER # Delete a todo
$ ./todo done NUMBER # Complete a todo
$ ./todo help # Show usage
$ ./todo report # Statistics"""
sys.stdout.buffer.write(s.encode('utf8'))
帮助函数:帮助函数用于提供用户如何使用待办事项列表的方式。帮助函数就像 todo 应用程序的文档。
蟒蛇3
# help function
def help():
sa = """Usage :-
$ ./todo add "todo item" # Add a new todo
$ ./todo ls # Show remaining todos
$ ./todo del NUMBER # Delete a todo
$ ./todo done NUMBER # Complete a todo
$ ./todo help # Show usage
$ ./todo report # Statistics"""
sys.stdout.buffer.write(sa.encode('utf8'))
函数添加项目在待办事项列表:添加的函数是用来增加新项目的待办事项列表
蟒蛇3
# function to add item in todo list
def add(s):
f = open('todo.txt', 'a')
f.write(s)
f.write("\n")
f.close()
s = '"'+s+'"'
print(f"Added todo: {s}")
打印待办事项列表函数,该函数用来打印存在于我们的待办事项列表中的项目。 Todo 项目按升序打印。
蟒蛇3
# Function to print the todo list items
def ls():
try:
nec()
l = len(d)
k = l
for i in d:
sys.stdout.buffer.write(f"[{l}] {d[l]}".encode('utf8'))
sys.stdout.buffer.write("\n".encode('utf8'))
l = l-1
except Exception as e:
raise e
函数来完成待办事项:函数定义完成的任务,这完成的任务在done.txt增加。
蟒蛇3
# Function to Complete a todo
def done(no):
try:
nec()
no = int(no)
f = open('done.txt', 'a')
st = 'x '+str(datetime.datetime.today()).split()[0]+' '+d[no]
f.write(st)
f.write("\n")
f.close()
print(f"Marked todo #{no} as done.")
with open("todo.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for i in lines:
if i.strip('\n') != d[no]:
f.write(i)
f.truncate()
except:
print(f"Error: todo #{no} does not exist.")
显示todolist统计信息的函数: “report”函数用于显示完整的统计信息。它打印已完成任务的总数和待处理任务的总数。
蟒蛇3
# Function to show report/statistics of todo list
def report():
nec()
try:
nf = open('done.txt', 'r')
c = 1
for line in nf:
line = line.strip('\n')
don.update({c: line})
c = c+1
print(
f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}')
except:
print(
f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}')
函数从待办事项列表中删除项目:DEL函数用于删除待办事项列表中的项目。它根据项目编号删除待办事项
蟒蛇3
# code
def deL(no):
try:
no = int(no)
nec()
# utility function defined in main
with open("todo.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for i in lines:
if i.strip('\n') != d[no]:
f.write(i)
f.truncate()
print(f"Deleted todo #{no}")
except Exception as e:
print(f"Error: todo #{no} does not exist. Nothing deleted.")
主要函数和实用函数
蟒蛇3
# code
def nec():
# utility function used in done and report function
try:
f = open('todo.txt', 'r')
c = 1
for line in f:
line = line.strip('\n')
d.update({c: line})
c = c+1
except:
sys.stdout.buffer.write("There are no pending todos!".encode('utf8'))
# Main program
if __name__ == '__main__':
try:
d = {}
don = {}
args = sys.argv
if(args[1] == 'del'):
args[1] = 'deL'
if(args[1] == 'add' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing todo string. Nothing added!".encode('utf8'))
elif(args[1] == 'done' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing NUMBER for marking todo as done.".encode('utf8'))
elif(args[1] == 'deL' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing NUMBER for deleting todo.".encode('utf8'))
else:
globals()[args[1]](*args[2:])
except Exception as e:
s = """Usage :-
$ ./todo add "todo item" # Add a new todo
$ ./todo ls # Show remaining todos
$ ./todo del NUMBER # Delete a todo
$ ./todo done NUMBER # Complete a todo
$ ./todo help # Show usage
$ ./todo report # Statistics"""
sys.stdout.buffer.write(s.encode('utf8'))
下面是实现:
蟒蛇3
# Complete code
import sys
import datetime
def help():
sa = """Usage :-
$ ./todo add "todo item" # Add a new todo
$ ./todo ls # Show remaining todos
$ ./todo del NUMBER # Delete a todo
$ ./todo done NUMBER # Complete a todo
$ ./todo help # Show usage
$ ./todo report # Statistics"""
sys.stdout.buffer.write(sa.encode('utf8'))
def add(s):
f = open('todo.txt', 'a')
f.write(s)
f.write("\n")
f.close()
s = '"'+s+'"'
print(f"Added todo: {s}")
def ls():
try:
nec()
l = len(d)
k = l
for i in d:
sys.stdout.buffer.write(f"[{l}] {d[l]}".encode('utf8'))
sys.stdout.buffer.write("\n".encode('utf8'))
l = l-1
except Exception as e:
raise e
def deL(no):
try:
no = int(no)
nec()
with open("todo.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for i in lines:
if i.strip('\n') != d[no]:
f.write(i)
f.truncate()
print(f"Deleted todo #{no}")
except Exception as e:
print(f"Error: todo #{no} does not exist. Nothing deleted.")
def done(no):
try:
nec()
no = int(no)
f = open('done.txt', 'a')
st = 'x '+str(datetime.datetime.today()).split()[0]+' '+d[no]
f.write(st)
f.write("\n")
f.close()
print(f"Marked todo #{no} as done.")
with open("todo.txt", "r+") as f:
lines = f.readlines()
f.seek(0)
for i in lines:
if i.strip('\n') != d[no]:
f.write(i)
f.truncate()
except:
print(f"Error: todo #{no} does not exist.")
def report():
nec()
try:
nf = open('done.txt', 'r')
c = 1
for line in nf:
line = line.strip('\n')
don.update({c: line})
c = c+1
print(
f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}')
except:
print(
f'{str(datetime.datetime.today()).split()[0]} Pending : {len(d)} Completed : {len(don)}')
def nec():
try:
f = open('todo.txt', 'r')
c = 1
for line in f:
line = line.strip('\n')
d.update({c: line})
c = c+1
except:
sys.stdout.buffer.write("There are no pending todos!".encode('utf8'))
if __name__ == '__main__':
try:
d = {}
don = {}
args = sys.argv
if(args[1] == 'del'):
args[1] = 'deL'
if(args[1] == 'add' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing todo string. Nothing added!".encode('utf8'))
elif(args[1] == 'done' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing NUMBER for marking todo as done.".encode('utf8'))
elif(args[1] == 'deL' and len(args[2:]) == 0):
sys.stdout.buffer.write(
"Error: Missing NUMBER for deleting todo.".encode('utf8'))
else:
globals()[args[1]](*args[2:])
except Exception as e:
s = """Usage :-
$ ./todo add "todo item" # Add a new todo
$ ./todo ls # Show remaining todos
$ ./todo del NUMBER # Delete a todo
$ ./todo done NUMBER # Complete a todo
$ ./todo help # Show usage
$ ./todo report # Statistics"""
sys.stdout.buffer.write(s.encode('utf8'))
输出: