如何获取可用的升级包列表并使用python将其写入文件?
当我运行apt-get upgrade > output
时
它适用于bash。我想我必须在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'
答案 0 :(得分: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评论中的链接
答案 1 :(得分:2)
使用Python模块subprocess
并关闭stdin
告诉子进程它应该退出。
答案 2 :(得分:0)
使用&gt;将输出重定向到文件是shell所做的事情。您的(更新的)代码正在传递&gt;相反,apt-get,它不知道如何处理它。将shell=True
添加到subprocess.Popen
的调用中将首先通过shell运行参数列表,这将使重定向工作。