Python Source Code Blocks in Org Mode

Table of Contents

Org Mode support for Python


Python is a high-level, readable, interpreted language which can be used for many common computing tasks. It runs on most modern operating systems. Python source code blocks are fully supported in Org Mode with a wide variety of Python-specific header arguments.

Python source code blocks in Org Mode can be used to define functions, filter and analyze data, create graphics and figures, and produce reproducible research papers.

Requirements and Setup

Python source code blocks in Org Mode require a working python installation. Python is included in Mac OS X and often in Gnu/Linux, and is easily available for Windows. Python installers are located at the Python download site.

Org Mode supports graphical output for LaTeX and HTML documents using Matplotlib.

To configure your emacs org-mode to use python, you'll need to ensure that org-babel-load-languages includes an entry for it. Typically, org-babel-load-languages will contain many entries. The example below omits other languages.

 '((python . t)))

Org Mode Features for Python Source Code Blocks

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.
  • :python: Name of the command for executing Python code.

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 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.
#+begin_src python :session
def foo(x):
  if x>0:
    return x+1
    return x-1


: 2
  • 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()
#+begin_src python
def foo(x):
  if x>0:
    return x+1

    return x-1

return foo(5)

: 6

Finally, if you are using matplotlib for graphics, matplotlib uses an "interactive" backend when started from an interactive python (as you might expect). So you have to set the backend explicitly to a PDF or PNG or other file-exporting backend when using session mode. See the example at

#+begin_src python :session :results file
import matplotlib
import matplotlib.pyplot as plt
'images/myfig.pdf' # return this to org-mode


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.

Examples of Use

  • Hello World!
#+begin_src python :results output
print "Hello, world!"

: 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
#+tblname: data_table
| a | 1 |
| b | 2 |
| c | 3 |
#+begin_src python :var val=1 :var data=data_table
# Return row specified by val.
# In non-session mode, use return to return results.

| b | 2 |

  • Plotting
#+begin_src python :results file
import matplotlib, numpy
import matplotlib.pyplot as plt
return 'images/python-matplot-fig.png' # return filename to org-mode




You need some care in order to pass utf-8 strings to python.

passing utf-8 strings to python

#+NAME: unicode_str
“this string is not ascii!”
#+NAME: error-in-passing-var
#+BEGIN_SRC python :var data=unicode_str
return data
#+RESULTS: error-in-passing-var

Will produce no output and prints the following message in the buffer *Org-Babel Error Output*:

  File "<stdin>", line 3
SyntaxError: Non-ASCII character '\xe2' in file <stdin> on line 3, but no encoding declared; see for details

passing utf-8 strings to python with workaround

A workaround is to use :preamble with the value # -*- coding:utf-8 -*-

#+NAME: ok-in-passing-var
#+BEGIN_SRC python :preamble "# -*- coding: utf-8 -*-" :var data=unicode_str
return data
#+RESULTS: ok-in-passing-var
: “this string is not ascii!”

Documentation from the website (either in its HTML format or in its Org format) is licensed under the GNU Free Documentation License version 1.3 or later. The code examples and css stylesheets are licensed under the GNU General Public License v3 or later.