繁体   English   中英

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

[英]How to make a variable inside a try/except block public?

如何在 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 块之外可用?

try语句不会创建新范围,但如果对url lib.request.urlopen的调用引发异常,则不会设置text 您可能希望在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)

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

print(locals())

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM