Activating virtualenv via Java ProcessBuilder Activating virtualenv via Java ProcessBuilder unix unix

Activating virtualenv via Java ProcessBuilder


You can activate a Python virtual environment in bash (and perhaps zsh) and Python, but not in Java or any other environment. The main thing to understand is that virtual environment activation doesn't do some system magic — the activation script just changes the current environment, and Python virtual environments are prepared to changes shell or Python but nothing else.

In terms of Java it means that when you call runCommandInDirectory() it runs a new shell, that new shell briefly activates a virtual env, but then the shell exits and all changes that "activates" the virtual env are gone.

This in turn means that if you need to run some shell or Python commands in a virtual env you have to activate the environment in every runCommandInDirectory() invocation:

String [] commands1 = new String [] {"/bin/bash", "-c", ". /Users/simeon/..../venv2.7/bin/activate; script1.sh"};runCommandInDirectory(path, commands)String [] commands2 = new String [] {"/bin/bash", "-c", ". /Users/simeon/..../venv2.7/bin/activate; script2.sh"};runCommandInDirectory(path, commands)

For Python scripts it's a bit simpler as you can run python from the environment and it automagically activates the environment:

String [] commands = new String [] {"/Users/simeon/..../venv2.7/bin/python", "script.py"};runCommandInDirectory(path, commands)