Check if Python Package is installed

前端 未结 16 1062
刺人心
刺人心 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条回答
  •  萌比男神i
    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
    

提交回复
热议问题