Python中未关闭的文件警告

时间:2019-03-12 09:40:07

标签: python-3.x apt

我编写了以下代码:

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:未关闭的文件<_io.TextIOWrapper名称= 44模式='w'   encoding ='UTF-8'> cache.commit

     

ResourceWarning:未关闭的文件<_io.TextIOWrapper名称= 43模式='r'   encoding ='UTF-8'> cache.commit()

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

我一直在阅读此书,并认为我应该将代码包装在一个“ with”语句中,这对于读取一个简单的文本文件很容易,但是我不知道该怎么做。图书馆。我认为这里最典型的调用是cache.close,我认为在调用 finally 时肯定会执行该调用。

1 个答案:

答案 0 :(得分:2)

python-apt repo的快速浏览表明,apt.cache.Cache()类实现了with关键字所需的两个方法,即__enter__()__exit__()。 / p>

这意味着您只需要做:

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]