Pythonのタスク管理プログラム

Oct 08 2020

Pythonで簡単なプログラムを作りました

  • タスクをファイルに保存します
  • ユーザーがそれらを管理できるようにします。

私の実装が効率的で、もっと良いことができるかどうか興味があります。すべてのデータをファイルからメモリにロードして、ファイルに再度保存することが、リスト保存タスクを実装するための良い方法であるかどうかはわかりません。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os


CHOICE_LIST_TASKS = 1
CHOICE_ADD_TASK = 2
CHOICE_REMOVE_TASK = 3
CHOICE_QUIT = 4


def read_int(prompt='> ', errmsg='Invalid number!'):
    num = None
    while num is None:
        try:
            num = int(input(prompt))
        except ValueError:
            print(errmsg)
    return num


def display_menu():
    print('What do you want to do?')
    print('[1] List all tasks')
    print('[2] Add a new task')
    print('[3] Delete task')
    print('[4] Quit')


choice = None
file = None
if not os.path.exists('tasks'):
    file = open('tasks', 'w+')
else:
    file = open('tasks', 'r+')
tasks = []

for line in file.readlines():
    tasks.append(line.strip())

while choice != CHOICE_QUIT:
    display_menu()
    choice = read_int()
    if choice == CHOICE_LIST_TASKS:
        if len(tasks) == 0:
            print('Task list is empty!')
        else:
            print('Tasks:')
            for x in tasks:
                print(x)
    elif choice == CHOICE_ADD_TASK:
        desc = input('Which task do you want to do? ')
        index = tasks.append(desc)
        print('Successfully added a new task!')
    elif choice == CHOICE_REMOVE_TASK:
        if len(tasks) == 0:
            print('Task list is empty!')
        else:
            for x in tasks:
                print(tasks.index(x), x)
            index = read_int('Which task do you want to delete? ')
            try:
                tasks.pop(index)
                print('Successfully deleted task!')
            except IndexError:
                print('Please enter proper task number')
    elif choice == CHOICE_QUIT:
        print('Good bye!')
    else:
        print('Invalid choice!')

file = open('tasks', 'w+')
for x in tasks:
    file.write(x + '\n')

回答

3 AryanParekh Oct 08 2020 at 20:53

一番上から始めましょう。

CHOICE_LIST_TASKS = 1
CHOICE_ADD_TASK = 2
CHOICE_REMOVE_TASK = 3
CHOICE_QUIT = 4

変数を作成して特定の整数を割り当てたいので、どこでもマジックナンバーを使用する必要がないことは明らかです。これは称賛に値します。Pythonでこのアイデアを実装するためのはるかに良い方法があります

列挙: Enum

Pythonでの列挙

列挙型は、
一意の定数値にバインドされた一連のシンボリック名(メンバー)です。

を作成する Enum

class Choices(Enum):
    list_task = 1
    add_task = 2 
    remove_task = 3
    quit = 4

これは、ランダムなグローバル変数よりもはるかに明確に見えます。列挙を繰り返し処理して、その値を名前で表示することもできます。

print(Choices.add_task.name)

add_task

print(Choices.add_task.value) 

1

より多くの機能を使用する

file = None
if not os.path.exists('tasks'):
    file = open('tasks', 'w+')
else:
    file = open('tasks', 'r+')
tasks = []

for line in file.readlines():
    tasks.append(line.strip())

これをという関数に移動できないのはなぜread_task_file()ですか?
このように、古いプロジェクトを1年読んだ後、私、あなた、あなた、そしてこのコードを読んだことのある人なら誰でも、これらの数行のコードがタスクファイルを読むことは非常に明白です。それがなければ、コードを完全に読み、その目的を理解する必要があります。

def read_task_file():
    file = None
    if not os.path.exists('tasks'):
        file = open('tasks', 'w+')
    else:
        file = open('tasks', 'r+')
    tasks = []
    for line in file.readlines():
        tasks.append(line.strip())
    return tasks

今タスクを取得することです

tasks = read_task_file()

これはまったく同じことが次のコードセットにも当てはまります。これにより、ユーザーは選択内容を入力して実行できるようになります。

ユーザーからの選択を読み取り、関数に実行する部分を因数分解すると、次のようになります。

def read_task_choice():
    display_menu()
    choice = read_int()
    if choice not in Choices._value2member_map_:
        print("Invalid input! Please enter a correct choice\n")
        read_task_choice()

注:Choices._value2member_map_列挙型のすべての値になります。

これはすでにずっときれいに見えます!すべてのケースをチェックするループに入れる必要がなくなりchoiceます。関数は、有効な入力がある場合にのみ戻ります。

私が言ったように、必要に応じて関数とそれらすべてに作業を除外します。私は4つの主要な仕事(4つの選択肢)について同じことをしました。


タスクを一覧表示する

def list_tasks(tasks):
    if len(tasks) == 0:
        print("Task list is empty!")
        return None


    for i in range(len(tasks)):
        print(f"{i} {tasks[i]}")

新しいタスクを追加する

def add_new_task(tasks):
    return input("What task would you like to finish ?: ")
    tasks.append(task)

タスクを削除

def remove_task(tasks):
    if len(tasks) == 0:
        print("Task list is already empty!")
        return None

    list_tasks(tasks)
    task = int(input(("Which task would you like to remove: ?")))

    if task < 0 or task >= len(tasks):
        print("Invalid input! Please select an appropriate task")
        remove_task(tasks)
    tasks.pop(task)

そして最後に

タスクファイルを更新する

def update_task_file(tasks):
    file = open('tasks', 'w+')
    for x in tasks:
        file.write(x + '\n')

私がすでに行ったようにすべてを置くことができるとき、何百万もの機能を持つことの意味は何ですか?今、あなたがゲームをしなければならないとき

tasks = read_task_file()

while True:
    choice = read_task_choice()
    if choice == Choices.list_task.value:
        list_tasks(tasks)

    elif choice == Choices.add_task.value:
        add_new_task(tasks)
        

    elif choice == Choices.remove_task.value:
        remove_task(tasks)

    else:
        break

    update_task_file(tasks)

これは、強く型付けされた関数を持つことの主な利点です。

画面をクリアして入力を待つ

グラフィックスがないため、いくつかの選択の後、端末が少し奇妙に見えることがわかります

選択するたびに画面をクリアし、ユーザーがキーを押すのを待つだけで、これを改善できます。

ターミナルのクリア

いくつかの方法があります。一般的な方法はos.system("cls")、Windowsを使用している場合に使用することですが、これを呼び出すと非常にコストがかかり、プログラムのプラットフォーム依存性も高まります。

できるよ

print(chr(27) + "[2J")

そして、これも機能します。

入力を待っています

この行input("Press any key to continue...")を追加すると、ユーザーの応答を待ってからすべての選択肢が再度表示されるため、エクスペリエンスが向上します。

最後の

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
from enum import Enum

class Choices(Enum):
    list_task = 1
    add_task = 2
    remove_task = 3
    quit = 4

def read_int(prompt='> ', errmsg='Invalid number!'):
    num = None
    while num is None:
        try:
            num = int(input(prompt))
        except ValueError:
            print(errmsg)
    return num

def display_menu():
    print('What do you want to do?')
    print('[1] List all tasks')
    print('[2] Add a new task')
    print('[3] Delete task')
    print('[4] Quit')

def read_task_file():
    file = None
    if not os.path.exists('tasks'):
        file = open('tasks', 'w+')
    else:
        file = open('tasks', 'r+')
    tasks = []
    for line in file.readlines():
        tasks.append(line.strip())
    return tasks

def update_task_file(tasks):
    file = open('tasks', 'w+')
    for x in tasks:
        file.write(x + '\n')

def read_task_choice():
    display_menu()
    choice = read_int()
    if choice not in Choices._value2member_map_:
        print("Invalid input! Please enter a correct choice\n")
        read_task_choice()
    return choice

def add_new_task(tasks):
    task = input("What task would you like to do: ")
    tasks.append(task)

def list_tasks(tasks):
    if len(tasks) == 0:
        print("Task list is empty!")
        return None


    for i in range(len(tasks)):
        print(f"{i} {tasks[i]}")

def remove_task(tasks):
    if len(tasks) == 0:
        print("Task list is already empty!")
        return None

    list_tasks(tasks)
    task = int(input(("Which task would you like to remove: ?")))

    if task < 0 or task >= len(tasks):
        print("Invalid input! Please select an appropriate task")
        remove_task(tasks)
    tasks.pop(task)

def clear_screen():
    print(chr(27) + "[2J")

def pause():
    input("Press any key to continue...")

tasks = read_task_file()

while True:
    clear_screen()
    choice = read_task_choice()
    if choice == Choices.list_task.value:
        list_tasks(tasks)

    elif choice == Choices.add_task.value:
        add_new_task(tasks)


    elif choice == Choices.remove_task.value:
        remove_task(tasks)

    else:
        break

    update_task_file(tasks)
    pause()