且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 python-apt API 安装包

更新时间:2022-12-13 11:43:04

推荐使用 python-apt Debian 软件包中的 apt 模块.这是底层 C/C++ libapt-xxx 库的高级包装器,并具有 Pythonic 接口.

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.

这是一个安装 libjs-yui-doc 包的示例脚本:

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))

与使用 apt-get 一样,它必须以超级用户权限运行才能访问和修改 APT 缓存.

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

$ sudo ./aptinstall.py

如果您尝试将软件包安装作为较大脚本的一部分,那么只在所需的最短时间内提升到 root 权限可能是个好主意.

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.

您可以在 /usr/share/pyshared/apt/progress/gtk2.py:_test() 函数中找到一个显示如何使用 GTK 前端安装软件包的小示例.

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.