|
| 1 | +# ModulesValidate (By David Maisonave aka Axter) |
| 2 | +# Description: |
| 3 | +# Checks if packages are installed, and optionally install packages if missing. |
| 4 | +# The below example usage code should be plave at the very top of the scource code before any other imports. |
| 5 | +# Example Usage: |
| 6 | +# import ModulesValidate |
| 7 | +# ModulesValidate.modulesInstalled(["watchdog", "schedule", "requests"]) |
| 8 | +# Testing: |
| 9 | +# To test, uninstall packages via command line: pip uninstall -y watchdog schedule requests |
| 10 | +import sys, os, pathlib, platform, traceback |
| 11 | +# ToDo: Add logic to optionally pull package requirements from requirements.txt file. |
| 12 | +# Add logic to report error sys.exit(126) -- 126 (0x7E) ERROR_MOD_NOT_FOUND: The specified module could not be found. |
| 13 | + |
| 14 | +def modulesInstalled(moduleNames, install=True, silent=False): |
| 15 | + retrnValue = True |
| 16 | + for moduleName in moduleNames: |
| 17 | + try: # Try Python 3.3 > way |
| 18 | + import importlib |
| 19 | + import importlib.util |
| 20 | + if moduleName in sys.modules: |
| 21 | + if not silent: print(f"{moduleName!r} already in sys.modules") |
| 22 | + elif isModuleInstalled(moduleName): |
| 23 | + if not silent: print(f"Module {moduleName!r} is available.") |
| 24 | + else: |
| 25 | + if install and (results:=installModule(moduleName)) > 0: |
| 26 | + if results == 1: |
| 27 | + print(f"Module {moduleName!r} has been installed") |
| 28 | + else: |
| 29 | + if not silent: print(f"Module {moduleName!r} is already installed") |
| 30 | + continue |
| 31 | + else: |
| 32 | + if install: |
| 33 | + print(f"Can't find the {moduleName!r} module") |
| 34 | + retrnValue = False |
| 35 | + except Exception as e: |
| 36 | + try: |
| 37 | + i = importlib.import_module(moduleName) |
| 38 | + except ImportError as e: |
| 39 | + if install and (results:=installModule(moduleName)) > 0: |
| 40 | + if results == 1: |
| 41 | + print(f"Module {moduleName!r} has been installed") |
| 42 | + else: |
| 43 | + if not silent: print(f"Module {moduleName!r} is already installed") |
| 44 | + continue |
| 45 | + else: |
| 46 | + if install: |
| 47 | + tb = traceback.format_exc() |
| 48 | + print(f"Can't find the {moduleName!r} module! Error: {e}\nTraceBack={tb}") |
| 49 | + retrnValue = False |
| 50 | + return retrnValue |
| 51 | + |
| 52 | +def isModuleInstalled(moduleName): |
| 53 | + try: |
| 54 | + __import__(moduleName) |
| 55 | + return True |
| 56 | + except Exception as e: |
| 57 | + pass |
| 58 | + return False |
| 59 | + |
| 60 | +def installModule(moduleName): |
| 61 | + try: |
| 62 | + if isLinux(): |
| 63 | + # Note: Linux may first need : sudo apt install python3-pip |
| 64 | + # if error starts with "Command 'pip' not found" |
| 65 | + # or includes "No module named pip" |
| 66 | + results = os.popen(f"pip --disable-pip-version-check --version").read() |
| 67 | + if results.find("Command 'pip' not found") != -1 or results.find("No module named pip") != -1: |
| 68 | + results = os.popen(f"sudo apt install python3-pip").read() |
| 69 | + results = os.popen(f"pip --disable-pip-version-check --version").read() |
| 70 | + if results.find("Command 'pip' not found") != -1 or results.find("No module named pip") != -1: |
| 71 | + return -1 |
| 72 | + if isFreeBSD(): |
| 73 | + print("Warning: installModule may NOT work on freebsd") |
| 74 | + pipArg = " --disable-pip-version-check" |
| 75 | + if isDocker(): |
| 76 | + pipArg += " --break-system-packages" |
| 77 | + results = os.popen(f"{sys.executable} -m pip install {moduleName}{pipArg}").read() # May need to be f"{sys.executable} -m pip install {moduleName}" |
| 78 | + results = results.strip("\n") |
| 79 | + if results.find("Requirement already satisfied:") > -1: |
| 80 | + return 2 |
| 81 | + elif results.find("Successfully installed") > -1: |
| 82 | + return 1 |
| 83 | + elif modulesInstalled(moduleNames=[moduleName], install=False): |
| 84 | + return 1 |
| 85 | + except Exception as e: |
| 86 | + pass |
| 87 | + return 0 |
| 88 | + |
| 89 | +def installPackage(package): # Should delete this. It doesn't work consistently |
| 90 | + try: |
| 91 | + import pip |
| 92 | + if hasattr(pip, 'main'): |
| 93 | + pip.main(['install', package]) |
| 94 | + else: |
| 95 | + pip._internal.main(['install', package]) |
| 96 | + except Exception as e: |
| 97 | + return False |
| 98 | + return True |
| 99 | + |
| 100 | +def isDocker(): |
| 101 | + cgroup = pathlib.Path('/proc/self/cgroup') |
| 102 | + return pathlib.Path('/.dockerenv').is_file() or cgroup.is_file() and 'docker' in cgroup.read_text() |
| 103 | + |
| 104 | +def isWindows(): |
| 105 | + if any(platform.win32_ver()): |
| 106 | + return True |
| 107 | + return False |
| 108 | + |
| 109 | +def isLinux(): |
| 110 | + if platform.system().lower().startswith("linux"): |
| 111 | + return True |
| 112 | + return False |
| 113 | + |
| 114 | +def isFreeBSD(): |
| 115 | + if platform.system().lower().startswith("freebsd"): |
| 116 | + return True |
| 117 | + return False |
| 118 | + |
| 119 | +def isMacOS(): |
| 120 | + if sys.platform == "darwin": |
| 121 | + return True |
| 122 | + return False |
| 123 | + |
| 124 | +def isWindows(): |
| 125 | + if any(platform.win32_ver()): |
| 126 | + return True |
| 127 | + return False |
0 commit comments