Remi-007
Remi-007

Reputation: 145

Python: How to script virtual environment building and activation?

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 it 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 ?

Upvotes: 7

Views: 8456

Answers (2)

Lu Chinke
Lu Chinke

Reputation: 683

I had to make one approach right now, so i will leave it here. You must have virtualenv installed. Hope helps someone :)

def setup_env():
    import virtualenv
    PROJECT_NAME = 'new_project'
    virtualenvs_folder = os.path.expanduser("~/.virtualenvs")
    venv_dir = os.path.join(virtualenvs_folder, PROJECT_NAME)
    virtualenv.create_environment(venv_dir)
    command = ". {}/{}/bin/activate && pip install -r requirements.txt".format(virtualenvs_folder, PROJECT_NAME)
    os.system(command)

Upvotes: 2

Eugene Yarmash
Eugene Yarmash

Reputation: 149776

The problem is that os.system('source test6_env/bin/activate') activates the virtual environment only for the subshell spawned by this particular 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 && . test6_env/bin/activate && pip install -r requirements.txt')

Alternatively, put your commands in a shell script and execute that with os.system() or, better yet, using a function from the subprocess module, e.g.

import subprocess
subprocess.run('/path/to/script.sh', check=True)

Upvotes: 9

Related Questions