Created
November 2, 2023 13:50
-
-
Save prahladyeri/c96817b6b4a33497642c643aa7ecae48 to your computer and use it in GitHub Desktop.
Python script to check if specified package(s) are installed. Scan the requirements.txt instead, if no package specified.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# Check if specified package(s) are installed. | |
# Displays a GUI message if any aren't and asks to install. | |
import sys, os | |
import subprocess | |
import re | |
import importlib.util | |
import tkinter as tk | |
import tkinter.messagebox as messagebox | |
def install_packages(*packages): | |
for pkg in packages: | |
subprocess.check_call([sys.executable, '-m', 'pip', 'install', pkg]) | |
def check(*packages): | |
##modules = ['csv', 'PIL', 'foob'] | |
if len(packages) == 0: | |
if not os.path.exists('requirements.txt'): return | |
packages = [] | |
pattern = "([a-zA-Z0-9_]*)([\s]*)([>|=|<]{0,2})([\s]*)(.*)" | |
for line in open('requirements.txt','r').read().splitlines(): | |
#print(pattern, line) | |
m = re.match(pattern, line) | |
#print("adding package %s from requirements.txt" % m[1]) | |
pkg = m[1] | |
if pkg.strip() == "": continue | |
packages.append( pkg) | |
not_found = [] | |
for pkg in packages: | |
print("checking package %s" % pkg) | |
try: | |
subprocess.check_output('py -m pip show ' + pkg, stderr=subprocess.STDOUT) | |
except subprocess.CalledProcessError as ex: | |
not_found.append(pkg) | |
print('missing...') | |
# if pkg in sys.modules: | |
# pass | |
# elif importlib.util.find_spec(pkg) is not None: | |
# pass | |
# else: | |
# not_found.append(pkg) | |
print("%d packages to be installed" % len(not_found)) | |
root = tk.Tk() | |
#root.overrideredirect(1) | |
root.withdraw() | |
if len(not_found) > 0: | |
ss = ",".join(not_found) | |
r = messagebox.askyesno("", "Package(s) not found:\n\n" + ss + "\n\nDo you want to install them?") | |
#print("R:", r) | |
if r: | |
install_packages(*not_found) | |
messagebox.showinfo("", "Package(s) installed successfully.") | |
root.destroy() | |
#return True | |
else: | |
messagebox.showinfo("", "All OK.") | |
def main(): | |
check() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment