- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to check if a python module exists without importing it?
To check if you can import something in Python 2, you can use imp module with try...except. For example,
import imp try: imp.find_module('eggs') found = True except ImportError: found = False print found
This will give you the output:
False
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:
True
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
Advertisements