20

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?

0

8 Answers 8

27

This is a pythonic way:

import apt
cache = apt.Cache()
if cache['package-name'].is_installed:
    print "YES it's installed"
else:
    print "NO it's NOT installed"
Sign up to request clarification or add additional context in comments.

2 Comments

You would get a key error in the case of a package not installed. There's another way to do it that would catch this and provide a neater output if the package is not found. I'll post this as a comment to the OP.
How to also install the package: stackoverflow.com/questions/17537390/…
7

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

1 Comment

This is wrong. dpkg -s will also return successfully (with a zero exit) if a package is in the state deinstall ok config-files, i.e. the package is not installed.
2

This is some code that would give you a neat way to display if the package is installed or not (without triggering a messy error message on the screen). This works in Python 3 only, though.

import apt
cache = apt.Cache()
cache.open()

response = "Package Installed."
try:
    cache['notapkg'].is_installed
except KeyError:
    response = "Package Not Installed."

print(response)

Comments

1

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)

3 Comments

These aren't the packages the OP is looking for. Python packages and Debian's package manager's packages are (largely) different things. See: en.wikipedia.org/wiki/Dpkg
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.
Google sent me here in search of this answer, so it is appreciated.
1

I needed a cross-platform compatible solution so I ended up using which.

import subprocess
retval = subprocess.call(["which", "packagename"])
if retval != 0:
    print("Packagename not installed!")

Although it's not as pythonic as the above answers it does work on most platforms.

1 Comment

Your soljution might work with packages such as wget, but not with packages such as coreutils
0

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.

1 Comment

commands is deprecated!
0

Inspired by the previous answers, this works nicely for both Python 2 and Python 3 and avoids try/catch for the key error:

import apt
package = 'foo' # insert your package name here
cache = apt.Cache()
package_installed = False

if package in cache:
    package_installed = cache[package].is_installed

1 Comment

In conda base environment (with Anaconda3) import apt gives the error: ModuleNotFoundError: No module named 'apt'. What would be the most proper solution to that?
0

I had the same doubt. Searched every corner in the Internet but couldn't find it. But finally after some Experiments I DID IT!!.

  • Code:
  1. import os
  2. packagename = "figlet" # Type in your package name
  3. os.system("dpkg -s "+packagename" | grep Status")

To type in any terminal using python codes:

  • Code:
  1. import os
  2. os.system("YOUR TERMINAL COMMAND HERE")

1 Comment

Unless there's a fringe case, there's no reason to use grep. Just read the exit code. def test_dpkgInstalled(packageName): return (os.system("dpkg -s " + packageName + "> /dev/null 2>&1")) == 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.