Skip to content

Instantly share code, notes, and snippets.

@antnieszka
Created November 1, 2019 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antnieszka/bdafd1503df2b97b4406065d0459669c to your computer and use it in GitHub Desktop.
Save antnieszka/bdafd1503df2b97b4406065d0459669c to your computer and use it in GitHub Desktop.
Create python venv and install dependencies in temp dir
import os
import tempfile
import subprocess
dependencies = """
flake8
black
""".strip()
# create temporary directory for venv
temp_dir_object = tempfile.TemporaryDirectory()
temp_dir = temp_dir_object.name
# create venv and install dependencies
retcode = subprocess.call(
["python", "-m", "venv", os.path.join(temp_dir, "venv")], shell=True
)
if retcode != 0:
raise RuntimeError("Failed to create venv")
python_path = os.path.join(temp_dir, "venv", "bin", "python")
if not os.path.isfile(python_path):
python_path = os.path.join(temp_dir, "venv", "Scripts", "python")
os.path.isfile(python_path)
retcode = subprocess.call([python_path, "-V"], shell=True)
if retcode != 0:
raise RuntimeError("Failed to find python")
requirements_path = os.path.join(temp_dir, "requirements.txt")
# write requirements to file and install into venv
with open(requirements_path, "w+") as req:
req.write(dependencies)
retcode = subprocess.call(
[python_path, "-m", "pip", "install", "-r", requirements_path], shell=True
)
if retcode != 0:
raise RuntimeError("Failed to install dependencies into venv")
# cleanup the mess
temp_dir_object.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment