Need to verify whether it is installed or not before the program can run.
Type in the shell:
pydoc modules .
This will list modules and you can grep the module which you want.
Found on stackoverflow here
You should use
list command with grep, that only lists installed packages (not all modules and their neighbours as well):
pip list | grep -F package_name
If package_name matches multiple installed packages e.g. searching for
botocore is also installed, then using
-w instead of
-F can help, as @TaraPrasadGurung suggests. This doesn't list the exact package, as
-w sees characters common in package names as word boundaries. So if you you have
requests-cache installed or
ruamel.yaml and ruamel.yaml.cmd` and need exactly one line of output you need to do something like:
pip list --disable-pip-version-check | grep -E "^ruamel\.yaml "
Please note that since
. matches any character when using
-E, you need to escape it.¹
¹ And yes that is necessary as there is a package
ruamel_yaml. Not every package manager is
pip compatible when dealing with namespace packages.
I have found existing answers incomplete and lacking good enough examples. Here is the solution I have settled on:
# an example checking if the pandas package is installed if python -c 'import pkgutil; exit(not pkgutil.find_loader("pandas"))'; then echo 'pandas found' else echo 'pandas not found' fi
A Github gist of this example can be found here: https://gist.github.com/shaypal5/d505af9953cd86f59c750fa600ee4ba6
You can also use something like this in your scripts.
python -c "import sys, pkgutil; sys.exit(0 if pkgutil.find_loader('$Package') else 1)"
What you'd get when a package is not installed.
Package=psutil python3 -c "import sys, pkgutil; sys.exit(0 if pkgutil.find_loader('$Package') else 1)" echo $? 1
What you'd get when a package is installed.
Package=requests python3 -c "import sys, pkgutil; sys.exit(0 if pkgutil.find_loader('$Package') else 1)" echo $? 0
Works in python2 and python3, and then you install based on the exit code.
I used a slightly stricter version of Anthon's answer, for use in a script:
pip3 list | grep -v "^Package *Version$" | grep -v "^-*$" | cut -d ' ' -f 1 | grep -xF "$package_name"
The first two greps are intended to strip the header lines from pip3's output.
The cut then selects only the package names (discarding the version numbers).
Then the final grep can perform an exact search for the relevant
If the package is found, it will display the package name, and return with exit code 0. If you don't want to see the package name, end the command with
Tested with pip3:
$> pip3 show MODULENAME
The exit-code ($?) would be "0" in case the module is installed, else "1".
Grepping has the problem of "false positives": The output of a
pip list | grep NAME
would match on any module which name contains "NAME", e.g. also match "some_other_NAME".
pip3 show MODULENAME
only matches on complete matches.