Check if Python Package is installed

前端 未结 16 1092
刺人心
刺人心 2020-12-02 05:59

What\'s a good way to check if a package is installed while within a Python script? I know it\'s easy from the interpreter, but I need to do it within a script.

I g

16条回答
  •  误落风尘
    2020-12-02 06:32

    If you mean a python script, just do something like this:

    Python 3.3+ use sys.modules and find_spec:

    import importlib.util
    import sys
    
    # For illustrative purposes.
    name = 'itertools'
    
    if name in sys.modules:
        print(f"{name!r} already in sys.modules")
    elif (spec := importlib.util.find_spec(name)) is not None:
        # If you choose to perform the actual import ...
        module = importlib.util.module_from_spec(spec)
        sys.modules[name] = module
        spec.loader.exec_module(module)
        print(f"{name!r} has been imported")
    else:
        print(f"can't find the {name!r} module")
    

    Python 3:

    try:
        import mymodule
    except ImportError as e:
        pass  # module doesn't exist, deal with it.
    

    Python 2:

    try:
        import mymodule
    except ImportError, e:
        pass  # module doesn't exist, deal with it.
    

提交回复
热议问题