【问题标题】:Python - How to make sure resource is closedPython - 如何确保资源已关闭
【发布时间】:2021-02-26 10:49:36
【问题描述】:

我想在从方法返回之前关闭 f。我添加了 finally 阻塞,但它需要初始化。用什么初始化它?

def test_close_resource(url):
    try:
        f = urllib2.urlopen(url)
        if f.code == 200:
            return True
    except Exception as error:
        return False
    finally:
        f.close()

【问题讨论】:

    标签: python urllib2


    【解决方案1】:

    使用with 在上下文管理器中打开连接:

    import urllib.request
    with urllib.request.urlopen('http://www.python.org/') as f:
        print(f.read(300))
    

    当连接离开使用with 关键字定义的上下文管理器块时,连接会自动关闭。

    【讨论】:

    • 但如果出现异常,它应该返回 false。
    • 您可以保留异常部分并删除finally 块。如果有任何异常,它们也会发生在 with 块中。
    【解决方案2】:

    我认为您正在寻找的是with 子句-

    with urllib.request.urlopen('http://python.org/') as response:pass
    

    【讨论】:

      猜你喜欢
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      相关资源
      最近更新 更多