通过使用 python apt,我可以安装软件包。在安装软件包之前和之后,我更新了缓存。但是,在安装软件包之前和之后,is_installed 返回相同的结果,换句话说,它给出了错误的结果。
安装包后,我需要检查包是否已安装。这是我的代码:
import apt.cache
def cache_update():
cache = apt.cache.Cache()
cache.update()
pkg = cache["p7zip-full"]
print pkg.is_installed # prints false
if pkg.is_installed:
print "it is already installed. Invalid request! "
pkg.mark_delete()
else:
print "it is not installed.Now you are installing..."
pkg.mark_install()
cache.commit()
print "DONE."
cache.update()
print pkg.is_installed # prints false.
if __name__ == '__main__':
cache_update()
答案1
由于某种原因,python 不会在 之后保留变量cache.commit()
。如果之后再次定义它,它会返回正确的pkg.is_installed
答案。
#!/usr/bin/python
import apt.cache
pack1 = 'p7zip-full'
def cache_update():
cache = apt.cache.Cache()
cache.update()
pkg = cache[pack1]
print pkg.is_installed # prints false
if pkg.is_installed:
print "it is already installed. Invalid request! "
pkg.mark_delete()
else:
print "it is not installed.Now you are installing..."
pkg.mark_install()
cache.commit()
print "DONE."
cache = apt.cache.Cache()
pkg = cache[pack1]
print pkg.is_installed # prints true.
if __name__ == '__main__':
cache_update()
答案2
您可以使用 open() 重新初始化,如下所示:
cache.commit()
cache.open()
print cache[pack1].is_installed