How to check if a module or a package is already installed in python3?

You should use pip's 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 boto when 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 and 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.


If the package doesn't do something crazy or time consuming on import you can try actually importing it:

if python -c "import package_name" &> /dev/null; then
    echo 'all good'
else
    echo 'uh oh'
fi

Type in the shell: pydoc modules .
This will list modules and you can grep the module which you want.
Found on stackoverflow here