Skip to content

Instantly share code, notes, and snippets.

@danield137
Created March 20, 2024 22:11
Show Gist options
  • Save danield137/d1849b10bf5bf95fe5593a91eeb6759c to your computer and use it in GitHub Desktop.
Save danield137/d1849b10bf5bf95fe5593a91eeb6759c to your computer and use it in GitHub Desktop.
Python autoinstall missing dependencies
import subprocess
import sys
import importlib
def install_modules(modules):
"""Install multiple Python modules using pip."""
subprocess.check_call([sys.executable, "-m", "pip", "install", *modules])
def install_dependencies(required_modules):
def wrapper(func):
modules_to_install = []
modules_to_load = []
for module in required_modules:
if isinstance(module, tuple):
installable, importable = module
else:
installable = module
importable = module
try:
importlib.import_module(importable)
except ImportError:
modules_to_install.append(installable)
modules_to_load.append(importable)
if modules_to_install:
print(f"Missing dependencies: {', '.join(modules_to_install)}.")
consent = input("Do you want to install them? (Y/N): ").strip().lower()
if consent == 'y':
print("Installing missing modules...")
install_modules(modules_to_install)
#for module in modules_to_load:
# globals()[module] = importlib.import_module(module)
print("All missing modules have been installed.")
else:
sys.exit("Script cannot run without the required dependencies.")
return func
return wrapper
@install_dependencies([
("sickit-learn", "sklearn"),
"tqdm"
])
def main():
# import as usual
import tqdm
import sklearn
print(sklearn.__version__)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment