You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  • PUT requires a key and value: Check if the split list has at least 3 elements
  • GET/DELETE only need a key: Check if the list has at least 2 elements
  • LIST needs no extra parameters: Directly process the dictionary

Fix Logical Bugs in Original Code

Your original code has several obvious bugs:

  1. When checking if a key exists, you used if "textA" in database: — this refers to the string literal "textA", not the variable textA. It should be if textA in database:
  2. The LIST command logic is wrong: It doesn't need a textA parameter, and the elif Command == 'LIST': was placed after an else clause, causing a syntax error
  3. The else branch's print("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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 21:17:47