Skip to content

Instantly share code, notes, and snippets.

@carlos-a-g-h
Last active April 21, 2024 17:48
Show Gist options
  • Save carlos-a-g-h/c294236df4d769216a0f1af434666364 to your computer and use it in GitHub Desktop.
Save carlos-a-g-h/c294236df4d769216a0f1af434666364 to your computer and use it in GitHub Desktop.
don't ask why
#!/usr/bin/python3
from pathlib import Path
from subprocess import run as sub_run
from subprocess import PIPE as sub_PIPE
def pip_list(filepath:Path)->bool:
print("\nObtaining list of packages...")
proc=sub_run(
["pip","list"],
stdout=sub_PIPE,stderr=sub_PIPE
)
if not proc.returncode==0:
return False
dump=""
packages_lines=proc.stdout.decode().splitlines()
for line in packages_lines:
if line.startswith("-"):
print("IGNORED:",line)
continue
if not len(line.split())==2:
print("ERROR with line:",line)
continue
parts=line.split()
if parts[0]=="Package" and parts[1]=="Version":
print("IGNORED:",line)
continue
dump=f"{dump}\n{parts[0]}=={parts[1]}"
filepath.parent.mkdir(exist_ok=True,parents=True)
filepath.write_text(dump.strip())
return True
def pip_dl(dependency:str,outdir:str)->bool:
print(f"\nDownloading: {dependency}")
proc=sub_run(
[
"pip","download",dependency,
"-d",outdir
],
stdout=sub_PIPE,
stderr=sub_PIPE
)
if proc.returncode==0:
return True
stdout_ok=proc.stdout.decode()
if len(stdout_ok)>0:
print(f"\nSTDOUT:\n{stdout_ok}")
stderr_ok=proc.stderr.decode()
if len(stderr_ok)>0:
print(f"\nSTDERR:\n{stderr_ok}")
return False
if __name__=="__main__":
from sys import argv as sys_argv
from sys import exit as sys_exit
command=sys_argv[1]
if command=="list":
path_outfile=Path(sys_argv[2])
if not pip_list(path_outfile):
sys_exit(1)
sys_exit(0)
if command=="download":
path_reqfile=sys_argv[2]
path_outdir=sys_argv[3]
lines=open(Path(path_reqfile)).readlines()
total=len(lines)
ok=0
for d in lines:
if pip_dl(d.strip(),path_outdir):
ok=ok+1
if ok>0:
print("\nDownloaded files:")
for fse in Path(path_outdir).iterdir():
print(f"\t{fse.name}")
print(f"\nFINAL RESULT:\n{ok} / {total}")
if not ok==total:
sys_exit(1)
sys_exit(0)
print("UNKNOWN COMMAND")
sys_exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment