imports with an auto install feature should the package be missing

PHOTO EMBED

Mon Aug 28 2023 22:27:21 GMT+0000 (Coordinated Universal Time)

Saved by @captainkyd #python

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__':
    imp = import_with_auto_install('{insert module name here}')
    print(imp)
content_copyCOPY

I have a lot of env setup and don't always remember which env I imported what into. This saves time over the script failing having to manually import the module to restart the program.