Created
June 23, 2025 13:39
-
-
Save aliakseis/9d90ac50261e5472267f8e726e2de483 to your computer and use it in GitHub Desktop.
Python install and import
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| import os | |
| import socket | |
| import importlib | |
| import subprocess | |
| def _install_and_import(package, | |
| alias=None, | |
| version=None, | |
| package_name=None, | |
| from_name=None): | |
| """ | |
| Import a package (or symbol) with optional alias and version. If missing, | |
| installs via pip3—favoring the VIRTUAL_ENV's pip if VIRTUAL_ENV is set. | |
| """ | |
| # Determine alias | |
| if alias is None: | |
| alias = from_name or package | |
| # Top-level name for pip install | |
| if package_name is None: | |
| package_name = package.split('.')[0] | |
| install_spec = package_name + (version or "") | |
| def find_pip(): | |
| # 1) If we're in a venv, use its pip | |
| venv = os.environ.get("VIRTUAL_ENV") | |
| if venv: | |
| # Windows | |
| win_pips = [ | |
| os.path.join(venv, "Scripts", "pip3.exe"), | |
| os.path.join(venv, "Scripts", "pip.exe"), | |
| ] | |
| # POSIX | |
| posix_pips = [ | |
| os.path.join(venv, "bin", "pip3"), | |
| os.path.join(venv, "bin", "pip"), | |
| ] | |
| for p in (win_pips + posix_pips): | |
| if os.path.isfile(p) and os.access(p, os.X_OK): | |
| return p | |
| # 2) Next, try to find pip3 in sys.prefix or next to the interpreter | |
| candidates = [ | |
| os.path.join(sys.prefix, "bin", "pip3"), | |
| os.path.join(sys.prefix, "bin", "pip"), | |
| os.path.join(os.path.dirname(sys.executable), "pip3"), | |
| os.path.join(os.path.dirname(sys.executable), "pip"), | |
| ] | |
| for p in candidates: | |
| if os.path.isfile(p) and os.access(p, os.X_OK): | |
| return p | |
| # 3) As a last resort, invoke pip as a module on the current interpreter | |
| return None # signal to use [sys.executable, "-m", "pip"] | |
| def run_pip(cmd, *args): | |
| """Helper to call pip or python -m pip""" | |
| if cmd: | |
| full = [cmd, "install", *args] | |
| else: | |
| full = [sys.executable, "-m", "pip", "install", *args] | |
| return subprocess.run(full, | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE, | |
| text=True) | |
| # Try to import first | |
| try: | |
| if from_name: | |
| mod = importlib.import_module(package) | |
| obj = getattr(mod, from_name) | |
| else: | |
| obj = importlib.import_module(package) | |
| except ImportError: | |
| pip_bin = find_pip() | |
| print(f"Installing '{install_spec}' via " | |
| f"{pip_bin or f'{sys.executable} -m pip'} …") | |
| res = run_pip(pip_bin, install_spec) | |
| if res.returncode != 0: | |
| print("!!! pip failed:\n", res.stderr) | |
| raise ImportError(f"Could not install {install_spec}") | |
| # Retry import | |
| try: | |
| if from_name: | |
| mod = importlib.import_module(package) | |
| obj = getattr(mod, from_name) | |
| else: | |
| obj = importlib.import_module(package) | |
| except ImportError: | |
| raise ImportError(f"Installed {install_spec} but still can't import") | |
| # Bind into globals under alias | |
| globals()[alias] = obj | |
| return obj | |
| #import torch | |
| #import cv2 | |
| #import numpy as np | |
| #from PIL import Image | |
| #from diffusers import StableDiffusionInpaintPipeline | |
| #_install_and_import("cv2") | |
| _install_and_import("cv2", package_name="opencv-python") | |
| _install_and_import("numpy", alias="np") | |
| #_install_and_import("PIL", from_name="Image") | |
| _install_and_import( | |
| "PIL.Image", # Python import path | |
| alias="Image", # name you’ll bind it to | |
| package_name="Pillow" | |
| ) | |
| # save old value (or None) | |
| _old = os.environ.get("PIP_INDEX_URL", None) | |
| # point pip at the CUDA index | |
| os.environ["PIP_INDEX_URL"] = "https://download.pytorch.org/whl/cu126" | |
| #torch = _install_and_import("torch") | |
| _install_and_import("torch", version="==2.7.0+cu126") | |
| # restore or delete | |
| if _old is None: | |
| del os.environ["PIP_INDEX_URL"] | |
| else: | |
| os.environ["PIP_INDEX_URL"] = _old | |
| _install_and_import("accelerate") | |
| _install_and_import("transformers") | |
| _install_and_import("xformers") | |
| _install_and_import("diffusers", from_name="StableDiffusionInpaintPipeline") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment