[Python] How to avoid modifying `sys.path` and handle dependencies when installing packages...

Discussão em 'Python' iniciado por Stack, Junho 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have a script to install packages from a shared repository. However, I need to modify sys.path and insert the link to the repository every time I import any libraries. Below is the script I used

    Is there a way to avoid modifying sys.path every time I import libraries?

    Additionally, I have the beautifulsoup4 wheel file in the shared repository, but I can't import it later because it asks me to download the dependency file typing_extensions. Normally, when using pip install, there's no need to manually install such dependencies. Is there a way to avoid installing typing_extensions manually? Any help would be greatly appreciated!

    import subprocess
    import os
    import sys
    import re

    shared_repo = r"C:..."
    wheel_dir = shared_repo

    installed, skipped, failed = [], [], []

    def is_already_in_shared(wheel_filename):
    m = re.match(r"^([A-Za-z0-9_.]+)-(\d+\.\d+\.\d+).*\.whl$", wheel_filename)
    if not m:
    return False

    pkg_name, pkg_version = m.group(1), m.group(2)
    dist_info = os.path.join(shared_repo, f"{pkg_name}-{pkg_version}.dist-info")
    return os.path.isdir(dist_info)

    if not os.path.isdir(wheel_dir):
    print(f"ERROR: wheel directory not found:\n {wheel_dir}")
    sys.exit(1)

    for fname in os.listdir(wheel_dir):
    if not fname.lower().endswith(".whl"):
    continue

    wheel_path = os.path.join(wheel_dir, fname)

    if os.path.getsize(wheel_path) == 0:
    print(f" Skipping empty/corrupt wheel: {fname}")
    skipped.append(fname)
    continue
    if is_already_in_shared(fname):
    print(f" Skipping {fname} — already in shared repo")
    skipped.append(fname)
    continue

    print(f"\nInstalling {fname} → {shared_repo}")
    result = subprocess.run(
    [
    sys.executable,
    "-m",
    "pip",
    "install",
    "--upgrade",
    "--target", shared_repo,
    wheel_path
    ],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True
    )

    if result.returncode == 0:
    print(f" Successfully installed: {fname}")
    installed.append(fname)
    else:
    print(f" FAILED to install: {fname}")
    failed.append(fname)
    error_file = os.path.join(wheel_dir, f"{fname}_error.txt")
    with open(error_file, "w", encoding="utf-8") as ef:
    ef.write(result.stderr)

    print("\nInstalled wheels: ", installed)
    print("Skipped wheels: ", skipped)
    print("Failed wheels: ", failed)

    if shared_repo not in sys.path:
    sys.path.insert(0, shared_repo)

    Continue reading...

Compartilhe esta Página