Making org-mode Python sessions look better

| categories: orgmode, python | tags:

Using sessions for python in org-mode has always bugged me a little bit. Mostly the appearance of >>> and … in the output. For example:

print 8
>>> >>> >>> 8

Today on the org-mode mailing list someone suggested a patch that might fix that up. Hopefully that patch makes it into org-mode, but if you run off of ELPA like I do it will be some time before it appears in your working version.

In the meantime, inspired by my recent post on updating multiple results, here we add a new hook function that removes these annoying characters from a Python session results section. Here is my version of this code. "^: >>>$"

(defun org-babel-python-strip-session-chars ()
  "Remove >>> and ... from a Python session output."
  (when (and (string=
              "python"
              (org-element-property :language (org-element-at-point)))
             (string-match
              ":session"
              (org-element-property :parameters (org-element-at-point))))

    (save-excursion
      (when (org-babel-where-is-src-block-result)
        (goto-char (org-babel-where-is-src-block-result))
        (end-of-line 1)
        ;(while (looking-at "[\n\r\t\f ]") (forward-char 1))
        (while (re-search-forward
                "\\(>>> \\|\\.\\.\\. \\|: $\\|: >>>$\\)"
                (org-element-property :end (org-element-at-point))
                t)
          (replace-match "")
          ;; this enables us to get rid of blank lines and blank : >>>
          (beginning-of-line)
          (when (looking-at "^$")
            (kill-line)))))))

(add-hook 'org-babel-after-execute-hook 'org-babel-python-strip-session-chars)
org-babel-python-strip-session-chars (lambda nil (org-refresh-images))
import matplotlib.pyplot as plt
plt.plot([3, 4, 5])
plt.show()

def f(s):
    x = 2 * s
    # blank lines look like indentation errors
    return x

print f(4)
[<matplotlib.lines.Line2D object at 0x10955c290>]
8
print f(9)
18

Here we can make an inline figure.

plt.figure()
plt.plot([3, 4.5, 5])
plt.savefig('images/session-fig.png')
'images/session-fig.png'

Not bad. It seems to work! Maybe this will make sessions more usable for me.

[2015-03-12 Thu] New corner case, do not cause an error when results are silenced.

print 6

Testing getting rid of blank lines and empty : >>> lines.

a = 2
b = 3
c = 4
print
print 'a=      ', a
print 'b =     ', b
print 'a + b = ', a+b
a=       2
b =      3
a + b =  5

Copyright (C) 2015 by John Kitchin. See the License for information about copying.

org-mode source

Org-mode version = 8.2.10

Discuss on Twitter