如何使 try/except 块内的变量公开?

新手上路,请多包涵

如何在 try/except 块中公开变量?

 import urllib.request

try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")

print(text)

此代码返回错误

NameError: name 'text' is not defined

如何使可变文本在 try/except 块之外可用?

原文由 user3348051 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 825
2 个回答

try 语句不会创建新范围,但是 text 如果调用 url lib.request.urlopen 引发异常-- 将不会被设置。您可能希望在 --- else 子句中使用 --- print(text) 行,以便仅在没有异常时执行。

 try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")
else:
    print(text)

如果 text 需要稍后使用,你真的需要考虑它的价值应该是什么如果分配给 page 失败并且你不能调用 page.read() 。您可以在 try 语句之前给它一个初始值:

 text = 'something'
try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")

print(text)

或者在 else 子句中:

 try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")
else:
    text = 'something'

print(text)

原文由 chepner 发布,翻译遵循 CC BY-SA 3.0 许可协议

正如之前回答的那样,使用 try except 子句没有引入新的范围,所以如果没有发生异常,你应该在 locals 列表中看到你的变量并且它应该可以在当前访问(在你的情况下全球)范围。

 print(locals())

在模块范围内(你的情况) locals() == globals()

原文由 4xy 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题