Created
November 1, 2019 22:36
-
-
Save antnieszka/bdafd1503df2b97b4406065d0459669c to your computer and use it in GitHub Desktop.
Create python venv and install dependencies in temp dir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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