Skip to content Skip to sidebar Skip to footer

Mercurial Update Hook Not Activating Python Virtual Environment

I have a bash script that I'm trying to execute anytime an hg update occurs. The goal of this bash script is to switch to the correct virtualenv. For the sake of simplicity, this s

Solution 1:

Your problem is that when you invoke a shell script, any changes to the environment variables do not get exported to the calling shell (hence why you need to call source activate from the surrounding shell).

The good news is that you don't strictly need to call activate in order to access a virtual environment. What activate will do is:

  1. Add the virtualenv's bin directory to $PATH.
  2. Set the VIRTUAL_ENV environment variable.
  3. Modify your prompt.

None of this is necessary in order to use the virtualenv, and you can execute the python binary in the virtualenv without ever using the script; the prompt is likely not relevant for your use case, you can add the directory (or just the python executable) to your path by symlinking it, and you need the VIRTUAL_ENV environment variable only for software that for some reason needs to be aware of the virtualenv it's running in. If necessary, you can figure it out from sys.executable. For example:

import sys, os

def find_venv():
  python = sys.executable
  for i in xrange(10):
    ifnotos.path.islink(python):
      break
    python = os.path.realpath(python)
  returnos.path.dirname(os.path.dirname(python))

ifnotos.environ.has_key("VIRTUAL_ENV"):
  os.environ["VIRTUAL_ENV"] = find_venv()

Post a Comment for "Mercurial Update Hook Not Activating Python Virtual Environment"