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
Open your command prompt type
pip3 list
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")
In the Terminal type
pip show some_package_name
Example
pip show matplotlib
If you mean a python script, just do something like this:
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")
try:
import mymodule
except ImportError as e:
pass # module doesn't exist, deal with it.
try:
import mymodule
except ImportError, e:
pass # module doesn't exist, deal with it.
if pip3 list | grep -sE '^some_command\s+[0-9]' >/dev/null
# installed ...
else
# not installed ...
fi
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