Skip to content

Instantly share code, notes, and snippets.

@seasonedgeek
Created May 3, 2020 02:51
Show Gist options
  • Save seasonedgeek/b53f71d01227e310c34e0ad4c2b52b5a to your computer and use it in GitHub Desktop.
Save seasonedgeek/b53f71d01227e310c34e0ad4c2b52b5a to your computer and use it in GitHub Desktop.
Alternative to processing a Python requirements file
#!/usr/bin/env python3
"""Checks the installation of packages, as recommended by the authors of
`Tiny Python Projects` (MEAP 6.0.0, Manning Publications 2020) to
learn by doing while enduring the covid-19 `stay safer @ home` orders.
See https://www.manning.com/books/tiny-python-projects?query=tiny.
"""
import shlex
import subprocess
def verify_requirements():
""" Verifies the following user installed packages"""
tools = [
"black",
"flake8",
"ipython",
"mypy",
"pylint",
"pytest",
"yapf",
"dephell",
]
for tool in tools:
# probe whereabouts within site package folder(s)?
if len(subprocess.getoutput(f"python3 -m pip list | grep {tool}")) == 0:
# perhaps tool is managed by homebrew?
if len(subprocess.getoutput(f"ls /usr/local/{tool}")) == 0:
# install tool
command_string = f"python3 -m pip install -U {tool}"
arguments = shlex.split(command_string)
process = subprocess.Popen(arguments)
# see ref 2
if process.returncode != 0:
message = utils.decode_utf8(process.stdout)
if len(message) == 0:
message = utils.decode_utf8(process.stderr)
raise CalledProcessError(message)
else:
print(f"Installed {tool}, in site packages.")
else:
print(f"Found {tool}, managed by homebrew.")
else:
print(f"Found {tool}, in site packages.")
if __name__ == "__main__":
try:
verify_requirements()
except subprocess.CalledProcessError as err:
print(err.output)
# Terminal stdout:
# Found black, managed by homebrew.
# Found flake8, in site packages.
# Found ipython, managed by homebrew.
# Found mypy, in site packages.
# Found pylint, in site packages.
# Found pytest, in site packages.
# Found yapf, in site packages.
# Found dephell, managed by homebrew.
# Could have run `python3 -m pip install -r requirements.txt` as an alternative,
# but what fun is there in that?
# References:
# 1. Python 3.8.1 API Subprocess management:
# https://docs.python.org/3/library/subprocess.html
# 2. Python Example: subprocess.CalledProcessError():
# https://www.programcreek.com/python/example/2244/subprocess.CalledProcessError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment