[Python] How to check if a library is installed at runtime in Python?

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página