How to check if a python module exists without importing it?

PythonServer Side ProgrammingProgramming

To check if you can import something in Python 2, you can use imp module with try...except. For example,

import imp
    found = True
except ImportError:
    found = False
print found

This will give you the output:


You can also use iter_modules from the pkgutil module to iterate over all modules to find if specified module exists. For example,

from pkgutil import iter_modules
def module_exists(module_name):
    return module_name in (name for loader, name, ispkg in iter_modules())
print module_exists('scrapy')

This will give the output:


This is because this module is installed on my PC.

Or if you just want to check it in the shell, you could use,

python -c "help('modules');" | grep yourmodule
Published on 21-Dec-2017 12:14:50