tags:

views:

57

answers:

3

Hello,

Is there an elegant and more Python-like way to check if a package is installed on Debian?

In a bash script, I'd do:

dpkg -s packagename | grep Status

Suggestions to do the same in a Python script?

Thanks,

+1  A: 

Have a look at commands. It's very useful for running things on the command line and getting the status.

Otherwise, I'm sure there is some library that will let you interact with apt. python-apt might work but it's a bit raw. Just capturing the command line seems easier.

Oli
+1  A: 

If you are checking for the existence of a package that installs a Python module, you can test for this from within a dependent Python script - try to import it and see if you get an exception:

import sys
try:
    import maybe
except ImportError:
    print "Sorry, must install the maybe package to run this program."
    sys.exit(1)
Paul McGuire
These aren't the packages the OP is looking for. Python packages and Debian's package manager's packages are (largely) different things. See: http://en.wikipedia.org/wiki/Dpkg
Oli
Well, the OP did ask if there was a way from within a Python script, so I don't think it was too far a leap to think he was looking for a way to detect a Python module dependency. Still, point taken, I hope I've more properly qualified my answer.
Paul McGuire
A: 

A slightly nicer, hopefully idiomatic version of your bash example:

import os, subprocess
devnull = open(os.devnull,"w")
retval = subprocess.call(["dpkg","-s","coreutils"],stdout=devnull,stderr=subprocess.STDOUT)
devnull.close()
if retval != 0:
    print "Package coreutils not installed."
loevborg