regex 在向自定义python命令提示符发出命令时,我收到一个错误

qojgxg4l  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(122)

由于我不知道问题的根源,我将张贴所有的代码(不多)。这是一个价值观错误:
这是我的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()

这是我的类在不同的文件

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

可能是正则表达式有问题,所以请检查一下。
下面是一个屏幕截图发生了什么:

它创建了一个值错误(非常肯定它的自我提升,但在这种情况下不应该发生)。请不要重写代码,除非有重大问题;我想自己解决这事。

vsdwdz23

vsdwdz231#

re.search不返回bool。它返回None或匹配对象。返回值永远不会等于True。更改以下内容:

if matches != True:
    raise ValueError

收件人:

if matches is None:
    raise ValueError

更新:正则表达式也不正确。下面是一个应该按预期工作的版本:

matches = re.search(r'^(create|open|kill|exit)(?:\s+-([^\s]+))?$', userInput)

在开始时有一个以上的^是不必要的。只需一个^即可将搜索锚到字符串的开头。另一个问题是指定可选的第二组的方式。原始的正则表达式有一个强制性的空格(它阻止了“exit”的工作),后面跟着一个可选的参数,该参数以-开头,后面跟着一个或多个嵌入的空格。所有空格都必须出现在-之前。以上纠正了这些问题。
顺便说一句,-在这些示例中似乎没有多大作用。如果需要的话,您可以很容易地消除它,但也许我们的意图是稍后扩展它,以允许前面有-的选项?

相关问题