Mercurial update hook not activating Python virtual environment

时光毁灭记忆、已成空白 提交于 2019-12-25 06:01:34

问题


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 script is called .test - shown as follows:

#!/bin/bash
echo 'testing hg update hook'
source ~/.virtualenvs/myvirtualenv/bin/activate

Whenever I call this script from my shell using source .test everythying works properly; I can see the results of echo and my shell changes to reflect the activated virtualenv

However,when I do an hg update, the virtualenv is not being activated. The script is firing as I can see the echo result; however, my shell is not updated to reflect the activated virtualenv. Below is the hook setup in my .hg/hgrc file is below. Any ideas why my virtualenv isn't being activated in this hook?

[hooks]
# Update to the correct virtualenv when switching branches (hg update branchname)
update = source .test

UPDATE 1: Per this answer, I don't believe the hg update hook is firing in my current shell; which is why the virtualenv activates when I run the script manually but fails from the hook


回答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):
    if not os.path.islink(python):
      break
    python = os.path.realpath(python)
  return os.path.dirname(os.path.dirname(python))

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


来源:https://stackoverflow.com/questions/33532382/mercurial-update-hook-not-activating-python-virtual-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!