Check if a Debian package is installed from Python

后端 未结 7 1545
一生所求
一生所求 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: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)
    

提交回复
热议问题