python - 如何在 try/except block 中公开变量?

标签 python python-3.x scope try-except

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

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 block 之外可用?

最佳答案

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)

关于python - 如何在 try/except block 中公开变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25666853/

相关文章:

python - IF 语句 Pandas Dataframe : The truth value of a Series is ambiguous

python - IronPython - 有没有办法从数据库加载 python 脚本或从字符串资源嵌入?

python - 为什么我的 Python PIL 导入不起作用?

javascript - 变量没有被正确分配,可能的范围问题(在 getJSON() 中的 each() 中有一个开关的函数)

python - 如何替换 Google 数据存储查询结果对象中的字符?

python - Pandas 在每行的列上进行整合

python - 对 pandas 中的数据框进行排序

c++ - 变量名前的"::"c++

python-3.x - 如何在Python3中仅捕获特定错误?

python - 如何在python中使用正则表达式匹配特定的时间和日期