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

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)

  • “try 语句不会创建新的作用域”这为我清除了很多事情,+1 (7认同)
  • 在最后一个片段中,如果没有例外,`text`将最终被赋予''something' (2认同)

Nis*_*ede 8

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)

  • // ,为什么这是必要的?Python 对于这个 `try` 和 ` except` 没有单独的块级作用域,据我所知,根据 http://stackoverflow.com/questions/17195569/using-a-variable-in-a-try-catch -finally-statement-without-declaring-it-outside。 (8认同)

4xy*_*4xy 5

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

print(locals())
Run Code Online (Sandbox Code Playgroud)

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