Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 901
Remi-007 Avatar asked Nov 05 '18 09:11

Remi-007


People also ask

How do you run a virtual environment in a Python script?

To use the virtual environment you created to run Python scripts, simply invoke Python from the command line in the context where you activated it. For instance, to run a script, just run python myscript.py .

What does it mean to activate a virtual environment Python?

Activating the virtual environment will change your shell's prompt to show what virtual environment you're using, and modify the environment so that running python will get you that particular version and installation of Python.


2 Answers

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)
like image 94
Eugene Yarmash Avatar answered Sep 25 '22 13:09

Eugene Yarmash


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)
like image 34
Lu Chinke Avatar answered Sep 23 '22 13:09

Lu Chinke