ob-doc-python.org 8.9 KB

Org Mode support for Python

Template Checklist [11/14] noexport

Introduction

  • [X] Revise #+TITLE:
  • [X] Indicate #+AUTHOR:
  • [X] Add #+EMAIL:
  • [X] Revise banner source block [3/3]
  • [X] Add link to a useful language web site
  • [X] Replace "Language" with language name
  • [X] Find a suitable graphic and use it to link to the language
  • web site
  • [X] Write an Introduction
  • [X] Describe Requirements and Setup
  • [X] Replace "Language" with language name in Org Mode Features for Language Source Code Blocks
  • [X] Describe Header Arguments
  • [X] Describe support for Sessions
  • [ ] Describe Result Types
  • [ ] Describe Other differences from supported languages
  • [X] Provide brief Examples of Use
  • [X] Add caveats about utf-8 in strings
  • [ ] Add caveats about utf-8 in tables
  • 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.

(org-babel-do-load-languages 'org-babel-load-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.

Sessions

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:

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

foo(1)

2
  • Non-session mode:

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

else: 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

import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig=plt.figure(figsize=(3,2)) plt.plot([1,3,2]) fig.tight_layout() plt.savefig('images/myfig.pdf') 'images/myfig.pdf' # return this to org-mode

images/myfig.pdf

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!

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
a 1
b 2
c 3

return(data[val])

b 2
  • Plotting

import matplotlib, numpy matplotlib.use('Agg') import matplotlib.pyplot as plt fig=plt.figure(figsize=(4,2)) x=numpy.linspace(-15,15) plt.plot(numpy.sin(x)/x) fig.tight_layout() plt.savefig('images/python-matplot-fig.png') return 'images/python-matplot-fig.png' # return filename to org-mode

images/python-matplot-fig.png

images/python-matplot-fig.png

Caveats

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

passing utf-8 strings to python

,#+BEGIN_EXAMPLE “this string is not ascii!” ,#+END_EXAMPLE


return data

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 http://www.python.org/peps/pep-0263.html for details

passing utf-8 strings to python with workaround

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


return data
“this string is not ascii!”