Skip to content

Instantly share code, notes, and snippets.

@stefanv
Last active November 4, 2023 21:45
Show Gist options
  • Save stefanv/0b052fa4014fa07e18e81fe544afc9f9 to your computer and use it in GitHub Desktop.
Save stefanv/0b052fa4014fa07e18e81fe544afc9f9 to your computer and use it in GitHub Desktop.
Install build or other dependencies from pyproject.toml
#!/usr/bin/env python
import tomllib
import argparse
import sys
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument(
"-e", "--extras",
help="Which extras to install; use `list` for options"
)
args = parser.parse_args()
config = tomllib.load(open("pyproject.toml", "rb"))
def get_config(key):
d = config
for subkey in key.split('.'):
try:
d = d[subkey]
except KeyError:
return None
return d
if args.extras is None:
# Install build dependencies
key = 'build-system.requires'
requires = get_config(key)
if requires is None:
print("Could not find build dependencies")
print(f"Ensure pyproject.toml has `{key}` key")
sys.exit(1)
else:
# Install extras
key = 'build-system.requires'
extra_requires = get_config("project.optional-dependencies")
if extra_requires is None:
print("Could not find extra dependencies")
print(f"Ensure pyproject.toml has `{key}` key")
sys.exit(1)
def print_extras():
print("`extras` can be one of:\n")
for key in extra_requires:
print(f"- {key}")
print()
if args.extras == 'list':
print_extras()
sys.exit(0)
if not args.extras in extra_requires:
print(
f"Extras `{args.extras}` not listed under "
"[[project.optional-dependencies]] in pyproject.toml.\n"
)
print_extras()
sys.exit(1)
requires = extra_requires[args.extras]
cmd = ["pip", "install"] + requires
print("$ " + " ".join(cmd))
subprocess.run(cmd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment