Check if a Debian package is installed from Python

Viewed 14503

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?

8 Answers

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

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