How to dynamically pip install a .whl file from python code and then use the library

Viewed 849

I am trying to pip install a .whl file dynamically (the name of the file will change each time I run it) and import it from the same python script. I tried running it in a different subprocess but I am not able to access the import from within the same file. I think python's importlib might have the answer but I haven't been able to figure it out.

import subprocess
import sys

@staticmethod
def install_file(lib):
    subprocess.check_call([sys.executable, "-m", "pip3", "install", lib]) 

# pip install the whl
install_file(whl_file_name)

# dynamically get the name of the .whl file and import it
whl = __import__(whl_file_name)

whl.do_something()

returns the following error

Traceback (most recent call last):
  File "<stdin>", line 12, in <module>
ModuleNotFoundError: No module named 'name_of_whl_file'
1 Answers

I had a similar problem. Solved it this way:

def install_file(package: str):
    subprocess.check_call([sys.executable, "-m", "pip", "install", "--no-cache-dir", "--no-index", "--find-links", "whlFolder", package], shell=True)

This method installs de package from the package name (e.g: 'tensorflow') instead of the filename, searching for the lib file in folder 'whlFolder'.

The package parameter must be informed with the package/ library name and the version (optionally). E.g:

#Installing the latest available version
install_file('tensorflow')

#Installing a specific version
install_file('tensorflow==2.2.0')
Related