76

如何在 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:名称“文本”未定义

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

4

3 回答 3

108

try语句不会创建新范围,但如果调用引发异常text则不会设置。url lib.request.urlopen您可能希望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:
    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)
于 2014-09-04T13:34:32.050 回答
5

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

print(locals())

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

于 2017-11-16T19:31:39.770 回答
3

只需在块text外声明变量,try except

import urllib.request
text =None
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!!")
if text is not None:
    print(text)
于 2014-09-04T13:38:17.170 回答