Question

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'
Was it helpful?

Solution

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

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top