7

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 ?

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
Remi-007
  • 145
  • 1
  • 11
  • Possible duplicate of [Activate virtualenv via os.system()](https://stackoverflow.com/questions/1691076/activate-virtualenv-via-os-system) – phd Nov 05 '18 at 12:25
  • https://stackoverflow.com/search?q=%5Bvirtualenv%5D+subshell – phd Nov 05 '18 at 12:26

2 Answers2

9

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)
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • Thank for for good explanation, it makes more sens now. Nevertheless I got with your command line 'source: not found'. Then I tried your alternative with putting the command 'source...... /bin/activate in a shell script . And I got the same error. Manually I have not problem to activate the virtualenv,. An idea ? – Remi-007 Nov 05 '18 at 11:47
  • Use `.` instead of `source`. `source` works in Bash, but not sh. – Eugene Yarmash Nov 05 '18 at 11:52
2

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)
Lu Chinke
  • 622
  • 2
  • 8
  • 27
  • virtualenv has dropped support for create_enviroment method. Instead it should use the cli_run method. Link to the docs here: https://virtualenv.pypa.io/en/latest/user_guide.html#programmatic-api – vladimir.gorea Apr 27 '20 at 12:19