Check if a Debian package is installed from Python

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

提交回复
热议问题