_ensure.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. This file is part of the UFONet project, https://ufonet.03c8.net
  5. Copyright (c) 2013/2026 | psy <epsylon@riseup.net>
  6. You should have received a copy of the GNU General Public License along
  7. with UFONet; if not, write to the Free Software Foundation, Inc., 51
  8. Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  9. """
  10. import sys, subprocess, importlib
  11. PIP_FLAGS = ["--no-warn-script-location", "--root-user-action=ignore", "--break-system-packages"]
  12. def pip_install(pip_name):
  13. print("[Info] [AI] [AUTO-INSTALL] Trying to install missing lib: '" + pip_name + "' ... -> [WAIT!]")
  14. cmd = [sys.executable, "-m", "pip", "install", pip_name] + PIP_FLAGS
  15. try:
  16. r = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
  17. except Exception as e:
  18. print("[Error] [AI] [AUTO-INSTALL] Could not run pip: " + str(e))
  19. return False
  20. if r.returncode != 0:
  21. err = (r.stderr or r.stdout or "").strip().splitlines()
  22. tail = "\n ".join(err[-6:]) if err else "(no output)"
  23. print("[Error] [AI] [AUTO-INSTALL] pip install '" + pip_name + "' failed:")
  24. print(" " + tail)
  25. return False
  26. print("[Info] [AI] [AUTO-INSTALL] '" + pip_name + "' installed -> [OK!]")
  27. return True
  28. def ensure(module_name, pip_name=None):
  29. pkg = pip_name or module_name
  30. try:
  31. return importlib.import_module(module_name)
  32. except ImportError:
  33. if not pip_install(pkg):
  34. print("[Error] [AI] You can install it manually with: python3 -m pip install " + pkg + " --break-system-packages")
  35. return None
  36. for cached in list(sys.modules):
  37. if cached == module_name or cached.startswith(module_name + "."):
  38. del sys.modules[cached]
  39. try:
  40. return importlib.import_module(module_name)
  41. except ImportError as e:
  42. print("[Error] [AI] Library still missing after install attempt: '" + module_name + "': " + str(e))
  43. print("[Error] [AI] You can install it manually with: python3 -m pip install " + pkg + " --break-system-packages")
  44. return None