gpt4 book ai didi

python - 名称错误 : global name 'AlreadyExists' is not defined when using try/except within a function

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:12 25 4
gpt4 key购买 nike

我知道存在很多这样的问题,但我似乎无法找到解决我遇到的问题的方法。

我有以下内容:

def function():
try:
# function to create a table on hbase
except AlreadyExists, ae:
print "WARN: " + ae.message

当我从另一个 python 脚本调用它时,它给了我

NameError: global name 'AlreadyExists' is not defined 

...但是如果我删除 def function() 并自行运行它,它就可以工作并且不会提示全局名称。

我尝试放置 global AlreadyExists 但没有用。我也看了这个similar problem但我不确定如何应用它,因为它可以独立运行(我不必导入任何特定的东西,但一旦我将它包装在一个函数中,它就会失败)。

有什么建议吗?

最佳答案

Python 仅在抛出异常时尝试访问名称。当您在函数外部运行代码时,它可能没有抛出异常,这就是您认为它有效的原因。

您需要从任何位置导入 AlreadyExists 异常。

关于python - 名称错误 : global name 'AlreadyExists' is not defined when using try/except within a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7720291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com