|
| 1 | +from subprocess import Popen, PIPE |
| 2 | +from os import listdir |
| 3 | +from os.path import isfile, join, splitext |
| 4 | +import click |
| 5 | +import random |
| 6 | +python_extension = ".py" |
| 7 | +mypath = "./" |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | +def install_libraries(lib): |
| 12 | + p = Popen(["pip3", "install", lib], stdout=PIPE, stderr=PIPE) |
| 13 | + while p.poll() is None: |
| 14 | + l = p.stdout.readline() |
| 15 | + click.echo(l.decode('utf-8')) |
| 16 | + click.echo(p.stdout.read().decode("utf-8")) |
| 17 | + output, error = p.communicate() |
| 18 | + if p.returncode != 0: |
| 19 | + click.echo("\n\nERROR occured while installing librairies:") |
| 20 | + return error.decode('utf-8') |
| 21 | + else: |
| 22 | + return False |
| 23 | + |
| 24 | +def get_missing_libraries(traceback): |
| 25 | + tracebacks = traceback.split('\n') |
| 26 | + lib = [elem for elem in tracebacks if "ModuleNotFoundError" in elem] |
| 27 | + if not lib: |
| 28 | + return tracebacks[-5:] |
| 29 | + lib = str(lib) |
| 30 | + lib = lib.split("'") |
| 31 | + click.echo('\n'.join(tracebacks[-5:])) |
| 32 | + return lib[-2] |
| 33 | + |
| 34 | +def ispythonfile(pythonfile): |
| 35 | + return isfile(pythonfile) and splitext(pythonfile)[1] == python_extension |
| 36 | + |
| 37 | +def lunch_script(file_name): |
| 38 | + p = Popen(["python3", file_name], stdout=PIPE, stderr=PIPE) |
| 39 | + output, error = p.communicate() |
| 40 | + if p.returncode == 1: |
| 41 | + try: |
| 42 | + if "ModuleNotFoundError" in error: |
| 43 | + pass |
| 44 | + except TypeError: |
| 45 | + error = error.decode('utf-8') |
| 46 | + missing_lib = get_missing_libraries(error) |
| 47 | + if isinstance(missing_lib, list): |
| 48 | + click.echo("\n\nERROR occured while installing librairies:") |
| 49 | + click.echo("\n".join(missing_lib)) |
| 50 | + return |
| 51 | + click.echo("Installing "+missing_lib+"") |
| 52 | + error_lib = install_libraries(missing_lib) |
| 53 | + if error_lib: |
| 54 | + click.echo(error_lib) |
| 55 | + else: |
| 56 | + click.echo("Installation of "+missing_lib+" done") |
| 57 | + click.echo("-------------------------------------\n\n") |
| 58 | + lunch_script(file_name) |
| 59 | + return |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | +@click.command() |
| 64 | +def hello(all_files=True): |
| 65 | + click.echo("Thanks for using lib_install\n\n") |
| 66 | + if all_files: |
| 67 | + python_files = [f for f in listdir(mypath) if ispythonfile(join(mypath, f))] |
| 68 | + try: |
| 69 | + python_files.remove("script.py") |
| 70 | + except ValueError: |
| 71 | + pass |
| 72 | + for file_name in python_files: |
| 73 | + click.echo("++++++++++++++++++++++++++++++++") |
| 74 | + click.echo("Starting script for "+file_name+"") |
| 75 | + lunch_script(file_name) |
| 76 | + else: |
| 77 | + lunch_script(file_name) |
| 78 | +if __name__ == '__main__': |
| 79 | + hello() |
| 80 | + |
0 commit comments