Python 如何使try/except块中的变量成为公共的?
如何使try/except块内的变量成为公共的Python 如何使try/except块中的变量成为公共的?,python,python-3.x,scope,local-variables,try-except,Python,Python 3.x,Scope,Local Variables,Try Except,如何使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 y
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)
此代码返回一个错误
名称错误:未定义名称“文本”
如何使变量文本在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.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)
只需将变量text
声明在try
之外,除了
块
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)
正如前面所回答的,使用try except
子句没有引入新的作用域,因此如果没有发生异常,您应该在locals
列表中看到您的变量,并且它应该可以在当前(您的情况下是全局)作用域中访问
在模块范围内(您的案例)locals()==globals()
如果page=urllib.request.urlopen(url)
将引发异常,那么text
将是什么?如果要将其设置为某个值,可以在except范围内或在try except
块外执行。text
是url的标记。在except
案例中,从不指定text
。您可以在该块中或在尝试之前设置text=None
。这不是范围问题。如果问题中提到的错误是在没有通过except块中的print语句的情况下提出的,那么我认为异常没有被捕获//,根据,Python没有块范围。我认为OP希望在出现异常的情况下为text
提供一个默认值。因此,在try except范围外或else范围内使用默认值更新此答案可能会对他有所帮助。在最后一个代码段中,text
最终将始终被分配“something”
如果没有例外“try语句不创建新范围”这为我清除了很多东西,+1“else”子句对我不起作用,但初始值起作用在第三个示例中,除了@4xy提到的问题外,print(text)
仍然会导致原始namererror
如果page.read().decode('utf8')
引发异常。只有当text='something'
被移动到块中时,它才会起作用,除了
块。//,为什么需要这样做?Python对此try
和没有单独的块级作用域,除了、AFAIK和根据之外。
print(locals())