x0x*_*x0x 35 python scope local-variables python-3.x 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)
Run Code Online (Sandbox Code Playgroud)
此代码返回错误__CODE__.
如何在try/except块之外使变量文本可用?
che*_*ner 50
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)
Run Code Online (Sandbox Code Playgroud)
如果以后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)
Run Code Online (Sandbox Code Playgroud)
或在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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
正如之前回答的那样, usingtry except子句没有引入新的范围,因此如果没有发生异常,您应该在locals列表中看到您的变量,并且它应该可以在当前(在您的情况下为全局)范围内访问。
print(locals())
Run Code Online (Sandbox Code Playgroud)
在模块范围内(您的情况) locals() == globals()