babel: implement org-babel-load-session:* for R, clojure, gnuplot, python, ruby and sh
[rgr-org-mode.git] / contrib / babel / lisp / langs / org-babel-python.el
blob388fa655a68d16ef07c97cfd944bb25f66488706
1 ;;; org-babel-python.el --- org-babel functions for python evaluation
3 ;; Copyright (C) 2009 Eric Schulte
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 0.01
10 ;;; License:
12 ;; This program is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
27 ;;; Commentary:
29 ;; Org-Babel support for evaluating python source code.
31 ;;; Code:
32 (require 'org-babel)
33 (require 'python)
35 (org-babel-add-interpreter "python")
37 (add-to-list 'org-babel-tangle-langs '("python" "py" "#!/usr/bin/env python"))
39 (defun org-babel-execute:python (body params)
40 "Execute a block of Python code with org-babel. This function is
41 called by `org-babel-execute-src-block'."
42 (message "executing Python source code block")
43 (let* ((processed-params (org-babel-process-params params))
44 (session (org-babel-python-initiate-session (first processed-params)))
45 (vars (second processed-params))
46 (result-params (third processed-params))
47 (result-type (fourth processed-params))
48 (full-body (concat
49 (mapconcat ;; define any variables
50 (lambda (pair)
51 (format "%s=%s"
52 (car pair)
53 (org-babel-python-var-to-python (cdr pair))))
54 vars "\n") "\n" (org-babel-trim body) "\n")) ;; then the source block body
56 (result (org-babel-python-evaluate session full-body result-type)))
57 (or (cdr (assoc :file params)) result)))
59 (defun org-babel-prep-session:python (session params)
60 "Prepare SESSION according to the header arguments specified in PARAMS."
61 (let* ((session (org-babel-python-initiate-session session))
62 (vars (org-babel-ref-variables params))
63 (var-lines (mapcar ;; define any variables
64 (lambda (pair)
65 (format "%s=%s"
66 (car pair)
67 (org-babel-python-var-to-python (cdr pair))))
68 vars)))
69 (org-babel-comint-in-buffer session
70 (mapc (lambda (var)
71 (move-end-of-line 1) (insert var) (comint-send-input nil t)
72 (org-babel-comint-wait-for-output session)) var-lines))
73 session))
75 (defun org-babel-load-session:python (session body params)
76 "Load BODY into SESSION."
77 (save-window-excursion
78 (let ((buffer (org-babel-prep-session:python session params)))
79 (with-current-buffer buffer
80 (goto-char (process-mark (get-buffer-process (current-buffer))))
81 (insert (org-babel-chomp body)))
82 buffer)))
84 ;; helper functions
86 (defun org-babel-python-var-to-python (var)
87 "Convert an elisp var into a string of python source code
88 specifying a var of the same value."
89 (if (listp var)
90 (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
91 (format "%S" var)))
93 (defun org-babel-python-table-or-string (results)
94 "If the results look like a table, then convert them into an
95 Emacs-lisp table, otherwise return the results as a string."
96 (org-babel-read
97 (if (string-match "^\\[.+\\]$" results)
98 (org-babel-read
99 (replace-regexp-in-string
100 "\\[" "(" (replace-regexp-in-string
101 "\\]" ")" (replace-regexp-in-string
102 ", " " " (replace-regexp-in-string
103 "'" "\"" results)))))
104 results)))
106 (defvar org-babel-python-buffers '(:default . nil))
108 (defun org-babel-python-session-buffer (session)
109 (cdr (assoc session org-babel-python-buffers)))
111 (defun org-babel-python-initiate-session-by-key (&optional session)
112 "If there is not a current inferior-process-buffer in SESSION
113 then create. Return the initialized session."
114 (save-window-excursion
115 (let* ((session (if session (intern session) :default))
116 (python-buffer (org-babel-python-session-buffer session)))
117 (run-python)
118 (setq org-babel-python-buffers (cons (cons session python-buffer)
119 (assq-delete-all session org-babel-python-buffers)))
120 session)))
122 (defun org-babel-python-initiate-session (&optional session)
123 (unless (string= session "none")
124 (org-babel-python-session-buffer (org-babel-python-initiate-session-by-key session))))
126 (defvar org-babel-python-last-value-eval "_"
127 "When evaluated by Python this returns the return value of the last statement.")
128 (defvar org-babel-python-pp-last-value-eval
129 '("results = _"
130 "import pprint"
131 "org_babel_pp = pprint.PrettyPrinter()"
132 "org_babel_pp.pprint(results)")
133 "When evaluated by Python this pretty prints the value of the last statement.")
134 (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
135 "Used to indicate that evaluation is has completed.")
136 (defvar org-babel-python-wrapper-method
138 def main():
141 open('%s', 'w').write( str(main()) )")
142 (defvar org-babel-python-pp-wrapper-method
144 import pprint
145 def main():
148 open('%s', 'w').write( pprint.pformat(main()) )")
150 (defun org-babel-python-evaluate (buffer body &optional result-type)
151 "Pass BODY to the Python process in BUFFER. If RESULT-TYPE equals
152 'output then return a list of the outputs of the statements in
153 BODY, if RESULT-TYPE equals 'value then return the value of the
154 last statement in BODY, as elisp."
155 (if (not session)
156 ;; external process evaluation
157 (save-window-excursion
158 (case result-type
159 (output
160 (with-temp-buffer
161 (insert body)
162 ;; (message "buffer=%s" (buffer-string)) ;; debugging
163 (shell-command-on-region (point-min) (point-max) "python" 'replace)
164 (buffer-string)))
165 (value
166 (let ((tmp-file (make-temp-file "python-functional-results")))
167 (with-temp-buffer
168 (insert
169 (format
170 (if (member "pp" result-params)
171 org-babel-python-pp-wrapper-method
172 org-babel-python-wrapper-method)
173 (mapconcat
174 (lambda (line) (format "\t%s" line))
175 (split-string
176 (org-remove-indentation (org-babel-trim body)) "[\r\n]") "\n")
177 tmp-file))
178 ;; (message "buffer=%s" (buffer-string)) ;; debugging
179 (shell-command-on-region (point-min) (point-max) "python"))
180 (let ((raw (with-temp-buffer (insert-file-contents tmp-file) (buffer-string))))
181 (if (or (member "code" result-params) (member "pp" result-params))
183 (org-babel-python-table-or-string raw)))))))
184 ;; comint session evaluation
185 (org-babel-comint-in-buffer buffer
186 (let* ((raw (org-babel-comint-with-output buffer org-babel-python-eoe-indicator t
187 ;; for some reason python is fussy, and likes enters after every input
188 (mapc (lambda (statement) (insert statement) (comint-send-input nil t))
189 (split-string (org-babel-trim full-body) "[\r\n]+"))
190 (comint-send-input nil t) (comint-send-input nil t)
191 (if (member "pp" result-params)
192 (mapc (lambda (statement) (insert statement) (comint-send-input nil t))
193 org-babel-python-pp-last-value-eval)
194 (insert org-babel-python-last-value-eval))
195 (comint-send-input nil t) (comint-send-input nil t)
196 (insert org-babel-python-eoe-indicator)
197 (comint-send-input nil t)))
198 (results (delete org-babel-python-eoe-indicator
199 (cdr (member org-babel-python-eoe-indicator
200 (reverse (mapcar #'org-babel-trim raw)))))))
201 (unless (or (member "code" result-params) (member "pp" result-params))
202 (setq results (mapcar #'org-babel-python-read-string results)))
203 (case result-type
204 (output (org-babel-trim (mapconcat #'identity (reverse (cdr results)) "\n")))
205 (value
206 (if (or (member "code" result-params) (member "pp" result-params))
207 (car results)
208 (org-babel-python-table-or-string (org-babel-trim (car results))))))))))
210 (defun org-babel-python-read-string (string)
211 "Strip 's from around ruby string"
212 (if (string-match "'\\([^\000]+\\)'" string)
213 (match-string 1 string)
214 string))
216 (provide 'org-babel-python)
217 ;;; org-babel-python.el ends here