python apt-get list upgrades

ぐ巨炮叔叔 提交于 2019-12-24 07:16:14

问题


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'

回答1:


Why not use the python-apt module eg.

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

also read the link in badp's comment




回答2:


Use the Python module subprocess and close stdin to tell the child process that it should exit.




回答3:


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 of subprocess.Popen will run the argument list through the shell first, which will make the redirect work.



来源:https://stackoverflow.com/questions/3092613/python-apt-get-list-upgrades

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!