如何在try / except块public中创建一个变量?

时间:2014-09-04 13:31:18

标签: python python-3.x scope local-variables try-except

如何在try / except块public中创建一个变量?

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块之外使变量文本可用?

3 个答案:

答案 0 :(得分:36)

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的作业失败并且您无法调用{{1},那么您真的需要考虑其价值应该是多少? }。您可以在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

答案 1 :(得分:3)

如前所述,使用try except子句没有引入新范围,因此如果没有异常发生,您应该在locals列表中看到您的变量,并且它应该在当前可访问(在您的情况下为全局) )范围。

print(locals())

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

答案 2 :(得分:1)

只需在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)