python apt-get 列出升级

1 投票
3 回答
7158 浏览
提问于 2025-04-16 00:17

我想知道怎么用Python获取可用的升级包列表,并把它写入文件。

当我在bash中运行 apt-get upgrade > output 时,这个命令是可以正常工作的。我觉得在Python程序里,我需要发送一个中断信号(也就是按 Ctrl+C)。

有没有什么建议可以让我实现这个呢?


我现在在代码中尝试了这个:

#!/usr/bin/env python
import subprocess

apt = subprocess.Popen([r"apt-get", "-V", "upgrade", ">", "/usr/src/python/upgrade.log"], stdin=subprocess.PIPE)
apt_stdin = apt.communicate()[0]

但是它直接退出了,没能写入文件。


这个方法是可以的,但当我把它移植到其他Debian系统时出现了错误:

import apt

cache=apt.Cache()
cache.update()
cache.open(None)
cache.upgrade()
for pkg in cache.get_changes():
#       print pkg.name,  pkg.summary
        fileHandle = open('/tmp/upgrade.log', 'a')
        fileHandle.write(pkg.name + " - " + pkg.summary + "\n")

然后错误是……

/usr/lib/python2.5/site-packages/apt/__init__.py:18: FutureWarning: apt API not stable yet
  warnings.warn("apt API not stable yet", FutureWarning)
Traceback (most recent call last):
  File "apt-notify.py", line 13, in <module>
    for pkg in cache.get_changes():
AttributeError: 'Cache' object has no attribute 'get_changes'

3 个回答

0

使用 > 符号将输出重定向到文件是由命令行的外壳程序来处理的。你的(更新后的)代码把 > 符号传给了 apt-get,但 apt-get 不知道该怎么处理这个符号。要让重定向正常工作,可以在调用 subprocess.Popen 时加上 shell=True,这样参数列表会先通过外壳程序处理。

2

使用Python的一个模块叫做subprocess,并且关闭stdin,这样可以告诉子进程它应该退出了。

3

为什么不使用python-apt模块呢,比如下面这个:

import apt
cache=apt.Cache()
cache.update()
cache.open(None)
cache.upgrade()
for pkg in cache.getChanges():
    print pkg.sourcePackageName, pkg.isUpgradeable

另外,看看badp评论里的链接。

撰写回答