我试图编写代码,捕捉用户输入的命令中的错误并返回建议。你知道吗
例如,如果我输入turnleft(2,1),而实际的命令是turnleft(2,1),程序将返回:“哦,不!您键入:turnleft(2,1)。你是想打左转弯吗?““
到目前为止,如果错误在圆括号之前,程序将捕获我需要的所有错误。但现在我正在尝试编写能够捕获太多参数的代码。例如turnlift(3,2,1)将返回“看起来您在函数中输入了太多参数。尝试左转(2,1)。你知道吗
我该怎么做?你知道吗
此时,程序简单地返回:“哦,不!您键入:turnLeft(3,2,1)。你是说左转?“但我希望它能回复一个信息,说争论太多了。如何捕捉括号内的错误而不是括号外的错误?你知道吗
到目前为止,这是我的代码:
from Myro import *
import difflib
import __builtin__
errorBox = None
variableList = []
for key in calico.manager.scope.GetVariableNames():
variableList.append(key)
for key, value in __builtins__.iteritems():
variableList.append(key)
def formatError(error, text):
bestMatches = difflib.get_close_matches(text, variableList, 1)
beforeParn = text[0:text.find("(")]
afterParn = text[text.find("("):text.find(")")]
print ("\nOh no! You typed:")
print ("\n\t", text)
print ("\nDid you mean:")
if bestMatches:
print ("\n\t", bestMatches)
if not bestMatches:
bestMatchesParn = difflib.get_close_matches(beforeParn, variableList)
if bestMatchesParn:
print ("\n\t", bestMatchesParn)
if not bestMatchesParn:
print ("\n\tCommand not found.")
calico.manager["python"].engine.OnErrorCallback = formatError
目前没有回答
相关问题 更多 >
编程相关推荐