On Thu, May 19, 2016 at 8:18 AM, Ken Mankoff <mankoff@gmail.com> wrote:

Thanks for the example. This makes conda + Org work better than it has for me in the past. Unfortunately, one major issues is editing and running code outside of Org via (org-edit-special). Perhaps elpy will support conda environments soon.


I think Elpy works fine with conda environments - you just have to call pyvenv-activate with the desired path. 

You have inspired me to try and automate this for org source blocks (see org snippets below).  It is a bit clunky, but I got it to work.  Let me know what you think, and any stylistic corrections are welcome (my lisp skills are sadly lacking).   
 


* Automating Elpy virtual env configuration in babel source editing buffer
+ This function will automatically activate the virtual environment that corresponds to the current python executable path
+ It should be a harmless no-op if we are not in a python buffer
  #+BEGIN_SRC emacs-lisp
    (defun wjh/elpy-pyvenv-activate-from-babel-info (info)
      "Activate relevant conda virtual env in Babel source editing buffer.
    The :python source block parameter is inspected to determine the venv."
      (let* ((python-command (or (cdr (assoc :python (nth 2 info)))
                                 org-babel-python-command))
             (venv (replace-regexp-in-string "/bin/python$" "" python-command)))
        (when (string-match "/envs/" venv)
          (pyvenv-activate (expand-file-name venv)))))
  #+END_SRC
+ Then we need to make sure it is run whenever we edit a babel source block by doing something like =(wjh/elpy-pyvenv-activate-from-babel-info org-src--babel-info)=, and also to do =(pyvenv-deactivate)= when we leave
+ Unfortunately, there are no actual hooks that I can find for =org-edit-src-code= or =org-edit-src-exit=
+ For the activation part we can co-opt the =org-babel-edit-prep:python= function:
  #+BEGIN_SRC emacs-lisp
    (defun org-babel-edit-prep:python (info)
      (wjh/elpy-pyvenv-activate-from-babel-info info))
  #+END_SRC
  + Although this will break if =ob-python.el= decides to define =org-babel-edit-prep:python= one day
+ For the deactivation part, I can't see any other way than to use advice
  #+BEGIN_SRC emacs-lisp
    (advice-add 'org-edit-src-exit :after #'pyvenv-deactivate)
  #+END_SRC
+ One thing we have to remember is to install the elpy python package and dependencies in each virtual environment.  For instance:
  #+BEGIN_SRC sh
  source activate myenv
  pip install elpy rope_py3k importmagic autopep8 yapf jedi
  #+END_SRC

 

--

  Dr William Henney, Instituto de Radioastronomía y Astrofísica,
  Universidad Nacional Autónoma de México, Campus Morelia