How to check if a module is installed in Python and, if not, install it within the code?

EDIT – 2020/02/03 The pip module has updated quite a lot since the time I posted this answer. I’ve updated the snippet with the proper way to install a missing dependency, which is to use subprocess and pkg_resources, and not pip. To hide the output, you can redirect the subprocess output to devnull: import sys … Read more

Importing a library from (or near) a script with the same name raises “AttributeError: module has no attribute” or an ImportError or NameError

This happens because your local module named requests.py shadows the installed requests module you are trying to use. The current directory is prepended to sys.path, so the local name takes precedence over the installed name. An extra debugging tip when this comes up is to look at the Traceback carefully, and realize that the name … Read more

ImportError: cannot import name ‘…’ from partially initialized module ‘…’ (most likely due to a circular import)

For future readers, this can also happen if you name a python file the same name as a dependency your project uses. For example: I cannot have a file named retrying.py that is using the retrying package. Assuming I had the retrying package in my project, I could not have a file called retrying.py with … Read more

How can I do relative imports in Python?

The problem is that you’re running the module as ‘__main__’ by passing the mod1.py as an argument to the interpreter. From PEP 328: Relative imports use a module’s __name__ attribute to determine that module’s position in the package hierarchy. If the module’s name does not contain any package information (e.g. it is set to ‘__main__’) … Read more

How can I import a module dynamically given the full path?

For Python 3.5+ use (docs): import importlib.util import sys spec = importlib.util.spec_from_file_location(“module.name”, “/path/to/file.py”) foo = importlib.util.module_from_spec(spec) sys.modules[“module.name”] = foo spec.loader.exec_module(foo) foo.MyClass() For Python 3.3 and 3.4 use: from importlib.machinery import SourceFileLoader foo = SourceFileLoader(“module.name”, “/path/to/file.py”).load_module() foo.MyClass() (Although this has been deprecated in Python 3.4.) For Python 2 use: import imp foo = imp.load_source(‘module.name’, ‘/path/to/file.py’) foo.MyClass() … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)