I am required to make use of my local environment and also use a virtual environment for a specific tool but this tool have dependency issues with my local environment. (I am already aware of how to use a virtualEnv within a script, here I am trying to create a new Virtual Environment within the script.) I want to create a python virtual Environment within a python program while in runtime(Because I have to delete this env at the end of the program). Need this environment to pass to python subprocess as keyword argument env.
I know I can create a virtualEnv using commands as argument to python subprocess. I am looking for some other approach
-
Possible duplicate of Activate a virtualenv with a Python scriptNikaido– Nikaido2019年09月13日 09:53:41 +00:00Commented Sep 13, 2019 at 9:53
-
2@Nikaidoh No that is for how to use existing virtualEnv, not addressing how to create a new one within the script.Shubham Dadhich– Shubham Dadhich2019年09月13日 10:01:07 +00:00Commented Sep 13, 2019 at 10:01
-
1Why subprocess is not fulfilling your needs?Tomasz Sabała– Tomasz Sabała2019年09月13日 10:09:33 +00:00Commented Sep 13, 2019 at 10:09
2 Answers 2
To create a virtual env from inside a python script you can use the virtualenv python module.
It pretty much comes down to a single line of code.
import virtualenv
import os
venv_dir = os.path.join(os.path.expanduser("~"), ".venv")
virtualenv.create_environment(venv_dir)
You can then activate this environment by accessing the activate_this.py file in your .venv folder, and install custom packages using pip module.
3 Comments
install_wheel function of this package, which is used internally - however I have never tested whether it works. You can review the code yourself: github.com/pypa/virtualenv/blob/master/virtualenv.py subprocess.run to run the virtualenv's pip. If I'm not mistaken, it should be in the bin folder.from venv import create
from os.path import join, expanduser, abspath
from subprocess import run
dir = join(expanduser("~"), "my-venv")
create(dir, with_pip=True)
# where requirements.txt is in same dir as this script
run(["bin/pip", "install", "-r", abspath("requirements.txt")], cwd=dir)