Python: How to script virtual environment building and activation ?

2601 views python
0

I would like to write a python script that does 3 things :

  1. build a virtual environment with python3
  2. activate this new virtual env. ( bash: source myvirtenv/bin/acticate)
  3. install packages with a requirements.txt (bash: pip install -r )

In my project I use the normal virtualenviroment package . and I have to do i on a Debian machine.

I tried to mimic the bash command with os.system() but didn't make it with the code below.

import os
os.system('python3 -m venv test6_env')
os.system('source test6_env/bin/activate')
os.system( 'pip install -r requirements.txt --user')

Problem the virtualenv will not activated and the requirements not installed.

Is there a easy trick to script in python this 3 stepy nicely ?

Thank you for your help Rémi

answered question

2 Answers

5

You can create virtual environment from this.

virtualenv venv -p python3

and activate by

. venv/bin/activate

And install all package from file from this

pip install -r requirements.txt

posted this
12

The problem is that source test6_env/bin/activate activates the virtual environment only for the subshell used by that os.system() call, and not any subsequent ones. Instead, run all shell commands with a single call, e.g.

os.system('python3 -m venv test6_env && source test6_env/bin/activate && pip install -r requirements.txt --user')

posted this

Have an answer?

JD

Please login first before posting an answer.