pyufunc.import_package#
- pyufunc.import_package(pkg_name, options=None, verbose=True, auto_install=False)#
Import a python package and optionally install it when it is missing.
This function does not install packages by default. Pass
auto_install=Trueto opt in to installing a missing package with pip before importing it.- Parameters:
pkg_name (str) –
the package name, it can be a string or tuple or list. if it’s a string, it’s the package name for both installation and import.
- if it’s a tuple or list, it has two elements:
first element is the package name, for pip or conda installation; second element is the package name, for import the package;
eg: “numpy” or “numpy==1.19.5”; eg: (“pillow”, “PIL”); eg: [“pillow==8.3.1”, “PIL”]; eg: [“opencv-python”, “cv2”];
options (list, optional) – optional pip install arguments used only when auto_install=True. eg: ‘–force-reinstall’, ‘–ignore-installed’. If not provided and auto_install=True, this function installs into the active virtual environment (venv/conda). When no virtual environment is active, it falls back to ‘–user’.
verbose (bool, optional) – print the error message if the package is not available. Defaults to True.
auto_install (bool, optional) – install the missing package automatically. Defaults to False.
Note
- if the module name different from import name
eg. module name is ‘pillow’, import name is ‘PIL’
- please use tuple or list to specify the module name and import name
e.g. import_package((‘pillow’, ‘PIL’))
- Location:
The function defined in pyufunc/pkg_utils.py.
Examples
>>> numpy = import_package("numpy") # equal to "import numpy as numpy" >>> np = import_package("numpy") # equal to "import numpy as np"
>>> # not existed >>> numpy = import_package("numpy") >>> :Info: missing dependency numpy. Please install it manually or call import_package(..., auto_install=True).
>>> # specify the version >>> numpy = import_package("numpy==1.19.5", auto_install=True) >>> :Package numpy==1.19.5 not existed in current env, installing...
>>> # different name for installation and import >>> PIL = import_package(("pillow", "PIL")) >>> cv2 = import_package(["opencv-python", "cv2"], auto_install=True) >>> cv2 = import_package(["opencv-python", "cv2"], options=["--force-reinstall"], auto_install=True) >>> cv2 = import_package(["opencv-python==4.9.0.80", "cv2"], auto_install=True)
- Returns:
the imported package, or None when the package cannot be imported.
- Return type:
object | None