Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Python Virtual environment within a python script

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

like image 310
Shubham Dadhich Avatar asked Jul 27 '26 13:07

Shubham Dadhich


1 Answers

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.

like image 140
Epion Avatar answered Jul 29 '26 05:07

Epion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!