如何在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块之外使变量文本可用?
答案 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)