如何访问 NameError 中的名称?
How to access name in NameError?
我想捕获一个 NameError,然后访问该名称并使用它来提供更好的消息。如何在不解析错误消息的情况下访问导致错误的名称?
try:
love_bug = herbie
except NameError as err:
name = get_name(err)
print(name, 'unknown.')
换句话说,我如何在上面的代码中实现 get_name()?
如果我很好地理解了你的问题,你可以创建你自己的错误,如下所示:
class ValidateName(NameError):
def __init__(self, name):
# Call the base class constructor with the parameters it needs
super().__init__(self, "unknown name " + name) #or whatever you need to add
try:
love_bug = "herbie"
raise ValidateName(love_bug) #there is no point in raising the exception manually here, I did this only to show how the message is shown,obliviously somewhere in your code the exception is raised
except ValidateName as err:
print(err)
(ValidateName(...), 'unknown name herbie')
您必须从 NameError.args[0]
中提取名称:
>>> try:
... print(foo)
... except NameError as e:
... print(re.search("'(?P<name>.+?)'", e.args[0]).group('name'))
...
foo
def get_name(err):
last = err.find("' ")
return err[6:last]
try:
love_bug= heribie
except NameError as err:
print(get_name(err.args[0]), "unknown")
我想捕获一个 NameError,然后访问该名称并使用它来提供更好的消息。如何在不解析错误消息的情况下访问导致错误的名称?
try:
love_bug = herbie
except NameError as err:
name = get_name(err)
print(name, 'unknown.')
换句话说,我如何在上面的代码中实现 get_name()?
如果我很好地理解了你的问题,你可以创建你自己的错误,如下所示:
class ValidateName(NameError):
def __init__(self, name):
# Call the base class constructor with the parameters it needs
super().__init__(self, "unknown name " + name) #or whatever you need to add
try:
love_bug = "herbie"
raise ValidateName(love_bug) #there is no point in raising the exception manually here, I did this only to show how the message is shown,obliviously somewhere in your code the exception is raised
except ValidateName as err:
print(err)
(ValidateName(...), 'unknown name herbie')
您必须从 NameError.args[0]
中提取名称:
>>> try:
... print(foo)
... except NameError as e:
... print(re.search("'(?P<name>.+?)'", e.args[0]).group('name'))
...
foo
def get_name(err):
last = err.find("' ")
return err[6:last]
try:
love_bug= heribie
except NameError as err:
print(get_name(err.args[0]), "unknown")