Python 中的未关闭文件警告

Unclosed File Warning in Python

我写了下面的代码:

class LazyPackageLoader:
    def __init__(self, package_names):
        self.package_names = package_names

    def install_packages(self):
        try:
            cache = apt.cache.Cache()
            cache.update()
            cache.open()

            for package in self.package_names:
                pkg = cache[package]
                pkg.mark_install()

            cache.commit()

        except Exception as e:
            print (str(e))

        finally:
            cache.close()

    def show_all_packages(self):
        pkgs = list()
        cache = apt.Cache()

        for package in cache:
            if cache[package.name].is_installed:
                pkgs.append(package.name)

        cache.close()
        return pkgs

我这样称呼它:

class TestLazyPackageLoader(unittest.TestCase):
    def test_installed_package(self):
        packagelist = list()
        packagelist.append("ethtool")

        lpl = LazyPackageLoader(packagelist)
        lpl.install_packages()

        packages = lpl.show_all_packages()
        if "ethtool" in packages:
            self.assertEqual(True, True)


if __name__ == '__main__':
    unittest.main()

代码按预期工作,但我收到以下警告:

ResourceWarning: unclosed file <_io.TextIOWrapper name=44 mode='w' encoding='UTF-8'> cache.commit

ResourceWarning: unclosed file <_io.TextIOWrapper name=43 mode='r' encoding='UTF-8'> cache.commit()

我想这个警告很简单:存在一个未打开的文件,最终被 Python 关闭。

我一直在阅读这篇文章并认为我应该将代码包装在 'with' 语句中,这对于读取一个简单的文本文件来说很容易,但我不知道如何用这个库来做。我认为这里最典型的调用是 cache.close,我认为当 finally 被调用时它肯定会被执行。

快速查看 python-apt repo 表明 apt.cache.Cache() class 实现了 with 关键字所需的两个方法,即 __enter__()__exit__().

这意味着您只需要做:

with apt.cache.Cache() as c:
   # ... do your things with c ...

# here, c is closed 

您的代码示例:

def show_all_packages(self):
    with apt.cache.Cache() as cache:
        return [package.name for package in cache if cache[package.name].is_installed]