Python字典数据库命令行工具参数适配及异常处理技术咨询
Hey there! Let's tackle your problems one by one, starting with clarifying your doubts and then fixing the code issues:
First, Clarify Your Dictionary Storage Question
As long as your program is running (not closed), the key-value pairs in the database dictionary will persist. Since database is defined outside the while True loop, every operation in the loop modifies the same dictionary instance. The data will only be cleared if you restart the program.
Fix the Forced Parameter Splitting Issue
The core problem with your original code is that it forces unpacking the input into three variables (Command, textA, textB), which throws errors for commands like GET,a or LIST that don't need three parts. Here's how to solve this:
Step 1: Handle Input Flexibly
Split the input into a list first, then extract the command and corresponding parameters based on the command type:
parts = input().strip().split(',') if not parts: print("Please enter a valid command!") continue command = parts[0].upper() # Convert to uppercase to support case-insensitive input like "get" or "Put"
Step 2: Process Parameters for Different Commands
PUTrequires a key and value: Check if the split list has at least 3 elementsGET/DELETEonly need a key: Check if the list has at least 2 elementsLISTneeds no extra parameters: Directly process the dictionary
Fix Logical Bugs in Original Code
Your original code has several obvious bugs:
- When checking if a key exists, you used
if "textA" in database:— this refers to the string literal"textA", not the variabletextA. It should beif textA in database: - The
LISTcommand logic is wrong: It doesn't need atextAparameter, and theelif Command == 'LIST':was placed after anelseclause, causing a syntax error - The
elsebranch'sprint("Not exist!")is misleading; it should say "Invalid command!"
Add Exception Handling
Use try-except to catch input format errors (like invalid splits or missing parameters) and give user-friendly prompts:
Complete Optimized Code
database = {} while True: print("Please type commands like: PUT,key,value | GET,key | DELETE,key | LIST") try: parts = input().strip().split(',') if not parts: print("Empty input! Please enter a valid command.") continue command = parts[0].upper() if command == 'PUT': # Require key and value, check parameter count if len(parts) != 3: print("PUT command requires format: PUT,key,value") continue key = parts[1].strip() value = parts[2].strip() database[key] = value print("Success!") elif command == 'GET': # Require key, check parameter count if len(parts) != 2: print("GET command requires format: GET,key") continue key = parts[1].strip() if key in database: print(database[key]) else: print("Key not exist!") elif command == 'DELETE': # Require key, check parameter count if len(parts) != 2: print("DELETE command requires format: DELETE,key") continue key = parts[1].strip() if key in database: del database[key] print("Success!") else: print("Key not exist!") elif command == 'LIST': # No extra parameters needed, ignore extra parts if any if not database: print("Database is empty!") else: print("Current key-value pairs:") for k, v in database.items(): print(f"{k}: {v}") else: print("Invalid command! Available commands: PUT, GET, DELETE, LIST") except Exception as e: print(f"Error occurred: {str(e)}. Please check your input format.")
Alternative Optimization Options
Besides the above parameter splitting method, you can also:
- Use regular expressions to match command formats strictly, e.g.,
re.match(r'(PUT|GET|DELETE),(\w+)(?:,(\w+))?', input_str)to extract command, key, and value - Encapsulate each command's logic into separate functions (like
def put_command(key, value): ...) to make the code cleaner and easier to maintain
内容的提问来源于stack exchange,提问作者wanjeonhimdle

