How to install a package using the python-apt API

别等时光非礼了梦想. 提交于 2019-11-27 20:13:13
Austin Phillips

It's recommended to use the apt module from the python-apt Debian package. This is a higher level wrapper around the underlying C/C++ libapt-xxx libraries and has a Pythonic interface.

Here's an example script which will install the libjs-yui-doc package:

#!/usr/bin/env python
# aptinstall.py

import apt
import sys

pkg_name = "libjs-yui-doc"

cache = apt.cache.Cache()
cache.update()
cache.open()

pkg = cache[pkg_name]
if pkg.is_installed:
    print "{pkg_name} already installed".format(pkg_name=pkg_name)
else:
    pkg.mark_install()

    try:
        cache.commit()
    except Exception, arg:
        print >> sys.stderr, "Sorry, package installation failed [{err}]".format(err=str(arg))

As with the use of apt-get, this must be run with superuser privileges to access and modify the APT cache.

$ sudo ./aptinstall.py

If you're attempting a package install as part of a larger script, it's probably a good idea to only raise to root privileges for the minimal time required.

You can find a small example in the /usr/share/pyshared/apt/progress/gtk2.py:_test() function showing how to install a package using a GTK front-end.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!