Syntax error How to install and import Python modules at runtime?

How to install and import Python modules at runtime?



You can use pip to install packages at runtime and importlib.import_module(moduleName) to import module by using its name as a string. For example,

import pip
import importlib
def import_with_auto_install(package):
    try:
        return importlib.import_module(package)
    except ImportError:
        pip.main(['install', package])
    return importlib.import_module(package)
# Example
if __name__ == '__main__':
    scrapy = import_with_auto_install('scrapy')
    print(scrapy)

The above script installs the scrapy module and imports it when installation of the module completes.

Updated on: 2019-10-01T11:18:18+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements