python apt-get 列表升级
如何使用 python 获取可用升级包的列表并将其写入文件?
当我运行 apt-get update > 时输出 它在 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'
How can I get a list of upgrade packages available and write it to file using python?
When I run apt-get upgrade > output
it works in bash. I think I have to send the trap signal (Ctrl+C) in the python program.
Any suggestions on how to achieve this?
I tried this on the code now:
#!/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]
but it exits and does not write to the file.
This works but I am getting error when I port this to other Debian systems:
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")
and the error....
/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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用>将输出重定向到文件是 shell 所做的事情。您的(更新的)代码正在传递 >改为 apt-get,它不知道如何处理它。将
shell=True
添加到subprocess.Popen
的调用中将首先通过 shell 运行参数列表,这将使重定向起作用。Using > to redirect output to a file is something the shell does. Your (updated) code is passing the > to apt-get instead, which has no idea what to do with it. Adding
shell=True
to your invocation ofsubprocess.Popen
will run the argument list through the shell first, which will make the redirect work.使用 Python 模块
subprocess
并关闭stdin
告诉子进程它应该退出。Use the Python module
subprocess
and closestdin
to tell the child process that it should exit.为什么不使用 python-apt 模块,例如。
另请阅读 badp 评论中的链接
Why not use the python-apt module eg.
also read the link in badp's comment