Installing python module within code
The officially recommended way to install packages from a script is by calling pip's command-line interface via a subprocess. Most other answers presented here are not supported by pip. Furthermore since pip v10, all code has been moved to
pip._internal precisely in order to make it clear to users that programmatic use of pip is not allowed.
sys.executable to ensure that you will call the same
pip associated with the current runtime.
import subprocessimport sysdef install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package])
If you want to use
pip to install required package and import it after installation, you can use this code:
def install_and_import(package): import importlib try: importlib.import_module(package) except ImportError: import pip pip.main(['install', package]) finally: globals()[package] = importlib.import_module(package)install_and_import('transliterate')
If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.