How can I make a variable inside the try/except block 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)

This code returns an error

NameError: name 'text' is not defined

How can I make the variable text available outside of the try/except block?

推荐答案

try statements do not create a new scope, but text won't be set if the call to url lib.request.urlopen raises the exception. You probably want the print(text) line in an else clause, so that it is only executed when there is no exception.

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)

If text needs to be used later, you really need to think about what its value is supposed to be if the assignment to page fails and you can't call page.read(). You can give it an initial value prior to the try statement:

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)

or in the else clause:

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-3.x相关问答推荐

按小时和日期对Pandas 数据帧进行分组

如何计算累积几何平均数?

当我在正则表达式末尾使用斜杠时,为什么会得到不同的结果?

在不使用 split 函数的情况下从字符串中分割逗号(','),句号('.')和空格(' '),将字符串的单词附加到列表中

重复数组直到一定长度 groupby pandas

Python,Web 从交互式图表中抓取数据

无法理解此递归函数的分配和环境用法

无法使用 curve_fit() 在 python 中复制高斯函数的曲线拟合

非拉丁字符的Python正则表达式不起作用

如何在 VSCode 的在 Cloud Run Emulator 上运行/调试构建设置中添加 SQL 连接

通过 requests 库调用 API 获取访问令牌

Python:获取未绑定的类方法

有没有更好的方法来判断一个数字是否是两个数字的范围

Tkinter 窗口显示(无响应)但代码正在运行

Pylint 给我最后的新行丢失

Pandas 的 EMA 与股票的 EMA 不匹配?

如何在不使用 @hydra.main() 的情况下获取 Hydra 配置

将 numpy.float64 列表快速转换为 Python 中的浮点数

在 Alembic 迁移期间更新列内容

Python3 函数中没有标识符的单个 * 是什么意思?