3

I've tried to setup a python virtual environment following the top answer here: https://emacs.stackexchange.com/questions/24267/using-org-babel-to-enable-virtualenv/38047 I tried activating the virtual environment using two methods: source $PYENV/bin/activate and pyvenv-workon $PYENV. I expect to see the output of which python and which pip refer back to this virtual environment, but it uses the computer's primary python installation. The path to $VIRTUAL_ENV is correct, however. Similarly, the final code block does not use the virtual environment as expected either. Any ideas what I'm missing?

 #+BEGIN_SRC bash :dir ~/ :results drawer pwd python3 -m venv py3_venv #+END_SRC #+RESULTS: :RESULTS: /home/jj :END: #+BEGIN_SRC bash :dir ~/ :results raw drawer source py3_venv/bin/activate #+END_SRC #+RESULTS: :RESULTS: :END: https://emacs.stackexchange.com/questions/24267/using-org-babel-to-enable-virtualenv/38047 #+BEGIN_SRC elisp :session venv-py3 :results raw drawer (pyvenv-workon "py3_venv") #+END_SRC #+RESULTS: :RESULTS: nil :END: #+BEGIN_SRC sh :session venv-py3 echo $VIRTUAL_ENV echo $PYTHONPATH which python which pip #+END_SRC #+RESULTS: | /home/jj/.virtualenvs/py3_venv | | | | /home/jj/anaconda3/bin/python | | /home/jj/anaconda3/bin/pip | #+BEGIN_SRC python :results output :session venv-py3 import sys \ print('\n'.join(sys.path)) #+END_SRC #+RESULTS: : /home/jj/anaconda3/lib/python37.zip : /home/jj/anaconda3/lib/python3.7 : /home/jj/anaconda3/lib/python3.7/lib-dynload : /home/jj/anaconda3/lib/python3.7/site-packages 
5
  • Have you tried setting org-babel-python-command to the desired python executable in your .emacs file? Commented Jan 1, 2019 at 4:08
  • 1
    venv is a builtin implementation of virtualenv and the user guide for virtualenv states, "If you directly run a script or the python interpreter from the virtualenv’s bin/ directory (e.g. path/to/ENV/bin/pip or /path/to/ENV/bin/python-script.py) then sys.path will automatically be set to use the Python libraries associated with the virtualenv" (my emphasis). So merely setting org-babel-python-command is enough to essentially activate that venv. (See the caveat in the above link.) Commented Jan 1, 2019 at 4:27
  • This did the trick. Thank you! Commented Jan 14, 2019 at 6:04
  • Can one set org-babel-python-command for a single org-babel block using some keyword or something? Commented Oct 30, 2023 at 13:34
  • 1
    @unhammer do that with a header argument, pointing the the path of the executable. Something like :python /path/to/python/in/your/venv/python.3.13. Commented Aug 24 at 14:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.