From fbfd15d22971bbf518270bc601fc121d04a7236b Mon Sep 17 00:00:00 2001 From: MichaelYanNJU <171240518@smail.nju.edu.cn> Date: Mon, 25 May 2020 12:30:40 +0800 Subject: [PATCH] Optimize initializing handlding. Optimize some dummy operation. --- .gitignore | 1 + commands.py | 5 ++++- include.py | 19 +++++++++++++++---- main.py | 16 ---------------- 4 files changed, 20 insertions(+), 21 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bee8a64 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__ diff --git a/commands.py b/commands.py index 36b2ecb..489b7ea 100644 --- a/commands.py +++ b/commands.py @@ -43,9 +43,12 @@ def get_word(): try: with open(os.path.expanduser("~/.vocab/last_word.json"),"r") as f: i=json.load(f) - except json.decoder.JSONDecodeError: + except (json.decoder.JSONDecodeError, FileNotFoundError): i=0 words=read() + if words == []: + print("No words in current vocabulary list!", file = stderr) + exit() i+=randint(0,len(words)-1) i%=len(words) word=words[i] diff --git a/include.py b/include.py index 752e851..a4c3f5a 100644 --- a/include.py +++ b/include.py @@ -3,6 +3,10 @@ from sys import argv from sys import stderr def read(): + try: + os.mkdir(os.path.expanduser("~/.vocab")) + except FileExistsError: + pass try: with open(os.path.expanduser("~/.vocab/data.json"),"r") as f: try: @@ -11,11 +15,18 @@ def read(): print(os.path.expanduser("~/.vocab/data.json"+" can't be decoded."),file=stderr) print("See if it's set to a wrong authority",file=stderr) print("or the file is broken",file=stderr) - words=[] + print("Type Y to clear the file.", file=stderr) + if input() == 'Y': + write([]) + words=[] + else: + exit() return words except FileNotFoundError: - print(os.path.expanduser("~/.vocab/data.json"+" is not found."),file=stderr) - print("call "+argv[0]+" help for more information",file=stderr) + print(os.path.expanduser("~/.vocab/data.json"), "is not found.", file=stderr) + print("Initialize it with an empty list", file=stderr) + write([]) + return [] def write(words): try: @@ -23,4 +34,4 @@ def write(words): json.dump((words),f) except FileNotFoundError: print(os.path.expanduser("~/.vocab/data.json"+" is not found."),file=stderr) - print("call "+argv[0]+" help for more information",file=stderr) + print("call "+argv[0]+" --help for more information",file=stderr) diff --git a/main.py b/main.py index 4342b46..81b386c 100644 --- a/main.py +++ b/main.py @@ -1,22 +1,6 @@ from include import * import commands as cm -try: - os.mkdir(os.path.expanduser("~/.vocab")) -except FileExistsError: - pass - -try: - with open(os.path.expanduser("~/.vocab/data.json"),"r") as f: - try: - words=json.load(f) - except json.decoder.JSONDecodeError: - words=[] -except FileNotFoundError: - print(os.path.expanduser("~/.vocab/data.json"+" is not found."),file=stderr) - print("call "+argv[0]+" help for more information",file=stderr) - exit() - if len(argv)==1: cm.get_word() else: