install_packages.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import subprocess
  2. import sys
  3. def check_and_install_packages(packages):
  4. """
  5. Checks if the specified packages are installed, and if not, prompts the user
  6. to install them.
  7. Parameters:
  8. - packages: A list of dictionaries, each containing:
  9. - 'import_name': The name used in the import statement.
  10. - 'install_name': (Optional) The name used in the pip install command.
  11. Defaults to 'import_name' if not provided.
  12. - 'version': (Optional) Version constraint for the package.
  13. """
  14. for package in packages:
  15. import_name = package['import_name']
  16. install_name = package.get('install_name', import_name)
  17. version = package.get('version', '')
  18. try:
  19. __import__(import_name)
  20. except ImportError:
  21. user_input = input(
  22. f"This program requires the '{import_name}' library, which is not installed.\n"
  23. f"Do you want to install it now? (y/n): "
  24. )
  25. if user_input.strip().lower() == 'y':
  26. try:
  27. # Build the pip install command
  28. install_command = [sys.executable, "-m", "pip", "install"]
  29. if version:
  30. install_command.append(f"{install_name}{version}")
  31. else:
  32. install_command.append(install_name)
  33. subprocess.check_call(install_command)
  34. __import__(import_name)
  35. print(f"Successfully installed '{install_name}'.")
  36. except Exception as e:
  37. print(f"An error occurred while installing '{install_name}': {e}")
  38. sys.exit(1)
  39. else:
  40. print(f"The program requires the '{import_name}' library to run. Exiting...")
  41. sys.exit(1)