如何使用python-apt API安装软件包 [英] How to install a package using the python-apt API
问题描述
在使用Python时,我是一个新手,因此我先乞求宽恕:).就是说,我正在尝试制作一个脚本,其中包括一些Linux软件包.首先,我尝试按照此处中所述使用subopen.尽管这最终可以工作,但我偶然发现了 python-apt API ,由于我不是忠实粉丝,也不是重新发明轮子,所以我决定尝试一下.
I'm quite a newbie when it comes to Python, thus I beg foregiveness beforehand :). That said, I'm trying to make a script that, among other things, installs some Linux packages. First I tried to use subopen as explained here. While this can eventually work, I stumbled upon the python-apt API and since I'm not a big fan or re-inventing the wheel, I decided to give a try.
尝试使用python-apt安装软件包的示例/教程时出现问题.在搜索文档时,我发现了 PackageManager 类,其中包含一些用于安装软件包的方法.我尝试了一些简单的代码来使其工作:
Problem comes when trying to find examples/tutorials on installing a package using python-apt. Searching the documentation I found the PackageManager class that has some methods to install a package. I tried some simple code to get this working:
apt_pkg.PackageManager.install("python")
这似乎不那么容易,安装方法需要apt_pkg.PackageManager而不是纯字符串.因此,再看一点,我发现了这个例子看起来很有希望,但是我有点不愿意使用,因为我不太了解那里发生的事情.
This does not seem to work that easily, the install method expects apt_pkg.PackageManager instead of a plain String. Thus, looking a bit more, I found this example that looks promising, but I'm a bit reluctant to use since I don't really understand some of what is happening there.
然后,有人尝试使用python-apt安装软件包吗?还是我应该使用纯老式的subopen样式?
Then, has anyone tried to install a package using python-apt or should I go for using plain-old subopen style?
谢谢!
推荐答案
建议使用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.
这篇关于如何使用python-apt API安装软件包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!