Home > OS >  Activate virtual environment from a python script
Activate virtual environment from a python script

Time:06-17

I am trying to create a python script for automating some of my personal stuff. In the script, I first want to activate my virtual environment and then do some other tasks, (API calls and processing them). But in the script.py the command that is responsible for activating the virtual environment is not working. I have tried

import subprocess
subprocess.Popen(['D:/work/venv/scripts/activate'], shell=True) # Not Working
subprocess.run(['D:/work/venv/scripts/activate'], shell=True) # Not Working

But this is not activating venv, I have also tried, but this seems not to work

import os
os.system('D:/work/venv/scripts/activate') # Not Working

I have also tried

activate_this = 'D:/Work/venv/scripts/activate_this.py' # Not working
with open(activate_this) as f:
    code = compile(f.read(), activate_this, 'exec')
    exec(code, dict(__file__=activate_this))

None of the above worked In linux/ubuntu shell script does the job done

source venv/bin/activate

I want something similar but using python script, which will be able to activate the virtual environment in the shell/cmd

CodePudding user response:

Looks like this answer I linked doesn't work for Python 3, but in the comments for the answer in that post I found the following from @Calimo which worked for me:

activate_this_file = "/path/to/venv/bin/activate_this.py"
exec(compile(open(activate_this_file, "rb").read(), activate_this_file, 'exec'), dict(__file__=activate_this_file))

Edit: After some discussion it looks like the real issue was using subprocess without specifying the correct environment. By default subprocess spawns a new process using the global environment. Specify the desired virtual environment by providing the env arg when calling subprocess, ex after activating the virtual environment with the code above:

venv= os.environ.copy()
subprocess.check_all(["pip3", "install", "flask"], env=venv)
  • Related