Skip to content

Instantly share code, notes, and snippets.

Last active February 12, 2023 07:37
Show Gist options
  • Save Superbil/5899556 to your computer and use it in GitHub Desktop.
Save Superbil/5899556 to your computer and use it in GitHub Desktop.
[PyHUG] July: Use Python in Org-mode

[PyHUG] July: Use Python in Org-mode


What is Org-mode ?

Org mode is for keeping notes, maintaining TODO lists, planning projects, and authoring documents with a fast and effective plain-text system.

  • an outline extension with visibility cycling and structure editing
  • an ASCII system and table editor for taking structured notes
  • a TODO list editor
  • a full agenda and planner with deadlines and work scheduling
  • an environment in which to implement David Allen’s GTD system
  • a simple hypertext system, with HTML and LaTeX export
  • a publishing tool to create a set of interlinked web pages
  • an environment for literate programming

Org Mode support for Python

What is Emacs ?

Emacs is a editor

GNU Emacs is an extensible, customizable text editor—and more. At its core is an interpreter for Emacs Lisp, a dialect of the Lisp programming language with extensions to support text editing.

When I start use Emacs ?

I ask somebody “What editor do you use to write python?”, when I first at PyHUG.

Answer is Emacs, Vim, Emacs. So I start to use Emacs !

Why I still use it ?

  • You can hack it !
  • You don’t remove your hand from the keyboard.

Emacs is better than X

No good or bad, only it is appropriate


Vimer will say

from How to Learn Emacs: A Hand-drawn One-pager for Beginners

It’s good to do everything in Emacs.

I use Emacs to …

  • write code (python-mode)
  • use SCM (magit)
  • organizational life (org-mode)
  • write document (org-mode)
  • use shell (eshell)
  • use term (zsh)

Introduction Org-mode


Emacs < 24

install from elpa

Emacs >= 24

org-mode is already bundle in it.

Org-mode structure

Only highlight some structure I always use


Headlines define the structure of an outline tree. The headlines in Org start with one or more stars, on the left margin4 5. For example:

* Top level headline
** Second level
*** 3rd level
    some text
*** 3rd level
    more text

* Another top level headline

Plain lists

Unordered list items start with ‘-’, ‘+’, or ‘*’ as bullets.

** Lord of the Rings
     My favorite scenes are (in this order)
     1. The attack of the Rohirrim
     2. Eowyn's fight with the witch king
        + this was already my favorite scene in the book
        + I really like Miranda Otto.
     3. Peter Jackson being shot by Legolas
        - on DVD only
        He makes a really funny face when it happens.
     But in the end, no individual scenes matter but the film as a whole.
     Important actors in this film are:
     - Elijah Wood :: He plays Frodo
     - Sean Austin :: He plays Sam, Frodo's friend.  I still remember
       him very well from his role as Mikey Walsh in The Goonies.


draw plain table like this

| Name  | Phone | Age |
| Peter |  1234 |  17 |
| Bill  |  4321 |  25 |




plain URL-like links and activate them as clickable links. The general link format, however, looks like this:

[[link][description]] or [[link]]

Python Hsinchu User Group (Hsinchu) - Meetup

TODO items

just add TODO keyword at head, looks like this:

*** TODO Write documents about org-mode


Write documents about org-mode

Breaking tasks down into subtasks

* Organize Party [33%]
** TODO Call people [1/2]
*** TODO Peter
*** DONE Sarah
** TODO Buy food
** DONE Talk to neighbor


Organize Party [33%]
Call people [1/2]
Buy food
Talk to neighbor


Every item in a plain list can be made into a checkbox by starting it with the string ‘[ ]’. Use C-c C-c or mouse to change state.

* TODO Organize party [2/4]
  - [-] call people [1/3]
    - [ ] Peter
    - [X] Sarah
    - [ ] Sam
  - [X] order food
  - [ ] think about what music to play
  - [X] talk to the neighbors


Organize party [2/4]
  • [-] call people [1/3]
    • [ ] Peter
    • [X] Sarah
    • [ ] Sam
  • [X] order food
  • [ ] think about what music to play
  • [X] talk to the neighbors


Tags make use of the hierarchical structure of outline trees. If a heading has a certain tag, all subheadings will inherit the tag as well. For example, in the list

* Meeting with the French group      :work:
** Summary by Frank                  :boss:notes:
*** TODO Prepare slides for him      :action:


Meeting with the French group
Summary by Frank
Prepare slides for him

Code block

(defun org-xor (a b)
   "Exclusive or."
   (if a (not b) b))

Use python in org-mode


let org-babel can use python

 '((python . t)))

or customizable this org-babel-load-languages

Header Arguments

Language-Specific Header Arguments

  • :results {output, value}: Value mode is the default (as with other languages). In value mode you can use the following subtypes:
    • raw: value is inserted directly
    • pp: value is pretty-printed by python using pprint.pformat(%s), then inserted
    • file: value is interpreted as a filename to be interpolated when exporting; commonly used for graphics output.
  • :preamble: Preamble code, inserted before the body (not commonly used). Default is none.
  • :return: Value to return (only when result-type is value, and not in session mode; not commonly used). Default is None; in non-session mode use return() to return a value.

Common Header Arguments

  • :session [name]: default is no session.
  • :var data=data-table: Variables can be passed into python from org-mode tables as scalars or lists. See the org-mode manual for more details.
  • :exports {code, results, both, none}: Standard babel option for what to export.


Session can share

origin source

Session mode is fully supported in python, including named sessions. In session mode, each block is run in the same long-running python interactive interpreter session, as if you had typed that block into python. You can have multiple sessions, all independent.

Sessions can be used to define functions, set up variables, and share code between source blocks.

Session mode in python is slightly different from non-session mode, because in session mode you are talking to a single “interactive” python session. In python’s interactive mode, blank lines are special: they indicate the end of an indented block. So you have to write your org-mode python a little differently when using session mode.

Also, in non-session mode, the python code block will be wrapped in a function, so to return a value (in :results value mode) you have to use a return statement. In session mode, the python code is evaluated directly by the interpreter, not in a function context, and the last statement’s value will be automatically returned, so you must not use a return statement.

Session mode:

blank lines not OK in indented blocks, and don’t use return()
Source block is passed directly to interactive python;\ value is value of _ at end.

def foo(x):
  if x>0:
    return x+1
    return x-1

# _ = foo(1) is ok too

Non-session mode:

blank lines OK in indented blocks, and use return()
Entire source block will get indented and used as the body of main()

def foo(x):
  if x>0:
    return x+1

    return x-1

return foo(5)

Result Types

  • value: Value results are the value of the last expression evaluated in the code block. This is found in session mode using using the “_” special python interpreter variable.
  • output: Output results come from whatever the python code prints on stdout.

Example of use python in org-mode

Hello World!

print "Hello, world!"

Inline calling:

Two plus two equals src_python{return(2+2)}

when exported, e.g. to HTML or LaTeX/PDF, becomes:

Two plus two equals 4

Extracting data from an org-mode table

# Return row specified by val.
# In non-session mode, use return to return results.


import matplotlib, numpy
import matplotlib.pyplot as plt
return 'images/python-matplot-fig.png' # return filename to or


Copy link

drorata commented May 2, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment