python notebook in emacs org-mode

Table of Contents

Python notebook like jupyter notebook can be done in emacs in various ways(various jupyter packages, ein, ob-ipython, ob-python), the most simple way is to use org-babel’s python support with session.

As simple as

#+begin_src python :session
import numpy
#+end_src

should work.

1. Caveat: using venv with doom emacs

Take away: If you are using doomemacs, you need to have your virtual environment set before the first time you enter a session, i.e. when the python shell process is started, ideally with pyvenv package.(I don’t know any other way)

For some reason, vanilla emacs (emacs -q) spawned python inferior process (where your sessioned python codes are run) would inherent shell’s python virtual environment, while doomemacs spawned python inferior process won’t.

To test, in terminal activate a venv with source path/to/activate and open an org-mode file with the following source block, with emacs -q and your doomemacs command respectively, babel-execute the the following source block, and you can tell if the venv is loaded by checking if the venv path is present in the output.

#+begin_src python :session
import sys
sys.path
#+end_src

On my side, with no user-configuration to org-babel, the venv path is present with emacs -q but not emacs (my doomemacs command).

1.1. My results: after source ~/.virtualenvs/difussion/bin/activate

['', '/usr/lib/python311.zip', '/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload', '/home/linfeng/.virtualenvs/difussion/lib/python3.11/site-packages']
['', '/usr/lib/python311.zip', '/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload', '/usr/local/lib/python3.11/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.11/dist-packages']
['', '/usr/lib/python311.zip', '/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload', '/home/linfeng/.virtualenvs/difussion/lib/python3.11/site-packages']

Backlinks

emacs

Emacs is an editor featuring:

Author: Linfeng He

Created: 2024-04-03 Wed 20:17