最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to check if a library is installed at runtime in Python? - Stack Overflow

programmeradmin5浏览0评论

I want to check whether a library is installed and can be imported dynamically at runtime within an if statement to handle it properly.

I've tried the following code:

try:
    import foo
    print("Foo installed")
except ImportError:
    print("Foo not installed")

It works as intended but does not seem like the most elegant method.

I was thinking more of a method that returns a boolean indicating whether the library is installed, something like:

Class.installed("foo")  # returns a boolean

I want to check whether a library is installed and can be imported dynamically at runtime within an if statement to handle it properly.

I've tried the following code:

try:
    import foo
    print("Foo installed")
except ImportError:
    print("Foo not installed")

It works as intended but does not seem like the most elegant method.

I was thinking more of a method that returns a boolean indicating whether the library is installed, something like:

Class.installed("foo")  # returns a boolean
Share Improve this question edited Mar 10 at 21:56 toolic 62.3k21 gold badges79 silver badges128 bronze badges asked Mar 10 at 21:55 ZheiranzZheiranz 111 bronze badge 2
  • 6 Nope, try/except is the accepted and usual method. – Tim Roberts Commented Mar 10 at 21:58
  • This question is similar to: Check if module exists, if not install it. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – JonSG Commented Mar 11 at 14:11
Add a comment  | 

2 Answers 2

Reset to default 1

Use importlib.util for a clean check.

import importlib.util

if importlib.util.find_spec("library_name") is not None:  
    print("Installed")

This code defines a function that checks if a package is installed:

def is_installed(pkg):
    try:
        __import__(pkg)
        return True
    except ImportError:
        return False

if is_installed("foo"):
    print("Foo installed")
else:
    print("Foo not installed")

It uses __import__, which allows to pass the name of the module to be imported as a string.

发布评论

评论列表(0)

  1. 暂无评论