Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script to activate and keep open a Virtualenv

I need a python script that will activate a virtualenv, run another python program inside the virtualenv, and then close the virutalenv after the second python program closes. Here is my code:

import os
import subprocess
from subprocess import Popen

activate_dir = "C:/Users/JohnDoe/theprogram/Scripts/"
os.chdir(activate_dir)
subprocess.Popen(["activate.bat"])

cal_dir = "C:/Users/JohnDoe/theprogram/"
os.chdir(cal_dir)
os.system('python program_file.py')

However, when this code run, I get an import error from the program_file which means the virtualenv is not activated. How can I fix this?

Thanks

Edit: This is on a Windows environment.

like image 552
GreenSaber Avatar asked Sep 05 '17 13:09

GreenSaber


1 Answers

The issue is that you are creating a new process with subprocess.Popen(["activate.bat"]) that is using that virtual environment, you're not changing your environment. What you need to do is to either call the python script in the same process you span:

os.system("source activate;python -V")

Or you could write a shell script that starts the virtual environment and calls any python script you send to it. In bash (on linux) this would be:

#!/bin/bash
# start a virtual environment and call a python module
# usage: ./runVirenvPythonModule module.py
source activate
python $1 # this is the first cmd line argument passed in
like image 114
Simon Hobbs Avatar answered Sep 18 '22 00:09

Simon Hobbs