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

自定义Python命令行执行命令触发ValueError问题求助

自定义Python命令提示符触发非预期ValueError

我在运行自定义Python命令提示符时,触发了自行定义的ValueError,但这个错误本不该在当前场景出现。我怀疑问题出在正则表达式上,附上相关代码请帮忙检查,除非存在重大问题,请勿重写代码,我希望自行修复。

main.py

from cmdClass import *
import re
import os

mainObject = Cmd()
while True:
    try:
        userInput = str(input(f"${mainObject.getAccount()}: "))
        matches = re.search(r'^^(create|open|kill|exit) -(?:\s+([^\s]+))?$', userInput)
        if matches != True:
            raise ValueError
        else:
            command = matches.group(1)
            if matches.group(2) != None:
                parameter = matches.group(2)
    except FileNotFoundError:
        mainObject.programExit(f"Your parameter (file-name) was invalid")
    except ValueError:
        mainObject.programExit(f"Your input was invalid")
    except TypeError:
        mainObject.programExit(f"You passed unwanted arguments")
    
    if command == "create":
        try:
            mainObject.create(parameter)
        except NameError:
            mainObject.programExit("No argument was passed")
    elif command == "kill":
        try:
            mainObject.kill(parameter)
        except NameError:
            mainObject.programExit("No argument was passed")
    elif command == "open":
        try:
            mainObject.fileOpen(parameter)
        except NameError:
            mainObject.programExit("No argument was passed")
    elif command == "exit":
        mainObject.programExit()

Cmd类(另一个文件)

import os

class Cmd:
    def __init__(self):
        self.account = input("Account Name: ")
    def create(self, fileName):
        file = open(f"{self.account}_{fileName}", 'x')
    def programExit(self, exitMessage=None):
        exit(exitMessage)
    def kill(self, fileName):
        os.remove(fileName)
    def fileOpen(self, fileName):
        with open(fileName, 'a+') as file:
            for i in file.readlines():
                print(i)
            lineNum = 0
            while True:
                lineNum += 1
                line = input(f"{lineNum} ")
                if line != "q\?":
                    file.write(line)
                else:
                    break
    def getAccount(self):
        return self.account

报错情况

运行时输入命令后,程序直接触发"Your input was invalid"的退出提示,对应代码中自行抛出的ValueError。

核心问题排查

  1. 正则匹配结果判断逻辑错误:re.search()匹配成功时返回的是Match对象,匹配失败返回None。你当前用matches != True做判断,而Match对象和布尔值True直接比较会返回False,导致即使匹配成功也会触发ValueError。正确的判断应该是if not matches:。
  2. 正则表达式语法冗余:开头有重复的^符号,多余的^会干扰匹配逻辑,需去掉一个。
  3. 命令参数规则不兼容:当前正则强制要求所有命令必须带-和参数,但exit命令不需要参数,会导致输入exit直接匹配失败。同时\s+要求-和参数之间必须有空格,若输入无空格的格式(如create-test)也会匹配失败。

内容的提问来源于stack exchange,提问作者Sam64710

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:41:33