19

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?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985

8 Answers8

25

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"
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
maxadamo
  • 524
  • 6
  • 16
  • 2
    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. –  Aug 14 '17 at 14:38
  • 1
    How to also install the package: https://stackoverflow.com/questions/17537390/how-to-install-a-package-using-the-python-apt-api – Ciro Santilli OurBigBook.com Nov 18 '19 at 16:54
8

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
  • 1,774
  • 13
  • 18
  • 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. – josch Feb 05 '22 at 17:32
2

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)
PaulMcG
  • 62,419
  • 16
  • 94
  • 130
  • 3
    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 Aug 02 '10 at 17:03
  • 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. – PaulMcG Aug 02 '10 at 17:16
  • 2
    Google sent me here in search of this answer, so it is appreciated. – noah Feb 07 '14 at 22:57
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)
1

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
  • 235,628
  • 64
  • 220
  • 299
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.

Poutsi
  • 13
  • 4
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
zachfrey
  • 63
  • 8
  • 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? – Xfce4 Dec 17 '21 at 19:52
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")
  • 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` – Tyler Montney Oct 15 '21 at 21:24