tags:

views:

51

answers:

3

hi,

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 python program

any suggestions? on how to achieve this...

-krisdigitx


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")

this is 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  A: 

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

Aaron Digulla
it gives error...
krisdigitx
Instead of "> outputfile", you can use stdout=PIPE and get the output via `communicate`
Aaron Digulla
+1  A: 

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

gnibbler
According to the [example](http://apt.alioth.debian.org/python-apt-doc/library/apt.cache.html#example), you're missing the step of re- [`open()`](http://apt.alioth.debian.org/python-apt-doc/library/apt.cache.html#apt.cache.Cache.open) -ing the cache after doing the update.
badp
@badp, thanks. fixed it
gnibbler
cool that worked, thanks for that, now that i have made the script, its spewing out error on other systems..
krisdigitx
@krisdigitx, you'll have to make sure python-apt is installed on all those systems
gnibbler
yes, python-apt is installed
krisdigitx
i have posted the error on the question now, looks like a bug..
krisdigitx
+1  A: 

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.

Paul Kuliniewicz