Check if Python Package is installed

前端 未结 16 1038
刺人心
刺人心 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:22

    Open your command prompt type

    pip3 list
    
    0 讨论(0)
  • 2020-12-02 06:28

    As of Python 3.3, you can use the find_spec() method

    import importlib.util
    
    # For illustrative purposes.
    package_name = 'pandas'
    
    spec = importlib.util.find_spec(package_name)
    if spec is None:
        print(package_name +" is not installed")
    
    0 讨论(0)
  • 2020-12-02 06:28

    In the Terminal type

    pip show some_package_name
    

    Example

    pip show matplotlib
    
    0 讨论(0)
  • 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.
    
    0 讨论(0)
  • 2020-12-02 06:32
    if pip3 list | grep -sE '^some_command\s+[0-9]' >/dev/null
      # installed ...
    else
      # not installed ...
    fi
    
    0 讨论(0)
  • 2020-12-02 06:33

    If you want to have the check from the terminal, you can run

    pip3 show package_name
    

    and if nothing is returned, the package is not installed.

    If perhaps you want to automate this check, so that for example you can install it if missing, you can have the following in your bash script:

    pip3 show package_name 1>/dev/null #pip for Python 2
    if [ $? == 0 ]; then
       echo "Installed" #Replace with your actions
    else
       echo "Not Installed" #Replace with your actions, 'pip3 install --upgrade package_name' ?
    fi
    
    0 讨论(0)
提交回复
热议问题