Check if a Debian package is installed from Python

后端 未结 7 1490
一生所求
一生所求 2020-12-31 03: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 Stat         


        
相关标签:
7条回答
  • 2020-12-31 03:41

    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"
    
    0 讨论(0)
  • 2020-12-31 03:47

    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)
    
    0 讨论(0)
  • 2020-12-31 03:51

    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
    
    0 讨论(0)
  • 2020-12-31 03:56

    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)
    
    0 讨论(0)
  • 2020-12-31 03:58

    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.

    0 讨论(0)
  • 2020-12-31 04:04

    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."
    
    0 讨论(0)
提交回复
热议问题