]> code.delx.au - gnu-emacs/blob - lisp/org/ob-python.el
Merge from trunk.
[gnu-emacs] / lisp / org / ob-python.el
1 ;;; ob-python.el --- org-babel functions for python evaluation
2
3 ;; Copyright (C) 2009-2011 Free Software Foundation
4
5 ;; Author: Eric Schulte
6 ;; Dan Davison
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.7
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; Org-Babel support for evaluating python source code.
29
30 ;;; Code:
31 (require 'ob)
32 (require 'ob-ref)
33 (require 'ob-comint)
34 (require 'ob-eval)
35 (eval-when-compile (require 'cl))
36
37 (declare-function org-remove-indentation "org" )
38 (declare-function py-shell "ext:python-mode" (&optional argprompt))
39 (declare-function py-toggle-shells "ext:python-mode" (arg))
40 (declare-function run-python "ext:python" (&optional cmd noshow new))
41
42 (defvar org-babel-tangle-lang-exts)
43 (add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
44
45 (defvar org-babel-default-header-args:python '())
46
47 (defvar org-babel-python-command "python"
48 "Name of command for executing python code.")
49
50 (defvar org-babel-python-mode (if (featurep 'xemacs) 'python-mode 'python)
51 "Preferred python mode for use in running python interactively.
52 This will typically be either 'python or 'python-mode.")
53
54 (defvar org-src-preserve-indentation)
55
56 (defun org-babel-execute:python (body params)
57 "Execute a block of Python code with Babel.
58 This function is called by `org-babel-execute-src-block'."
59 (let* ((session (org-babel-python-initiate-session
60 (cdr (assoc :session params))))
61 (result-params (cdr (assoc :result-params params)))
62 (result-type (cdr (assoc :result-type params)))
63 (return-val (when (and (eq result-type 'value) (not session))
64 (cdr (assoc :return params))))
65 (preamble (cdr (assoc :preamble params)))
66 (full-body
67 (org-babel-expand-body:generic
68 (concat body (if return-val (format "return %s" return-val) ""))
69 params (org-babel-variable-assignments:python params)))
70 (result (org-babel-python-evaluate
71 session full-body result-type result-params preamble)))
72 (org-babel-reassemble-table
73 result
74 (org-babel-pick-name (cdr (assoc :colname-names params))
75 (cdr (assoc :colnames params)))
76 (org-babel-pick-name (cdr (assoc :rowname-names params))
77 (cdr (assoc :rownames params))))))
78
79 (defun org-babel-prep-session:python (session params)
80 "Prepare SESSION according to the header arguments in PARAMS.
81 VARS contains resolved variable references"
82 (let* ((session (org-babel-python-initiate-session session))
83 (var-lines
84 (org-babel-variable-assignments:python params)))
85 (org-babel-comint-in-buffer session
86 (mapc (lambda (var)
87 (end-of-line 1) (insert var) (comint-send-input)
88 (org-babel-comint-wait-for-output session)) var-lines))
89 session))
90
91 (defun org-babel-load-session:python (session body params)
92 "Load BODY into SESSION."
93 (save-window-excursion
94 (let ((buffer (org-babel-prep-session:python session params)))
95 (with-current-buffer buffer
96 (goto-char (process-mark (get-buffer-process (current-buffer))))
97 (insert (org-babel-chomp body)))
98 buffer)))
99
100 ;; helper functions
101
102 (defun org-babel-variable-assignments:python (params)
103 "Return list of python statements assigning the block's variables"
104 (mapcar
105 (lambda (pair)
106 (format "%s=%s"
107 (car pair)
108 (org-babel-python-var-to-python (cdr pair))))
109 (mapcar #'cdr (org-babel-get-header params :var))))
110
111 (defun org-babel-python-var-to-python (var)
112 "Convert an elisp value to a python variable.
113 Convert an elisp value, VAR, into a string of python source code
114 specifying a variable of the same value."
115 (if (listp var)
116 (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
117 (if (equal var 'hline)
118 "None"
119 (format
120 (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
121 var))))
122
123 (defun org-babel-python-table-or-string (results)
124 "Convert RESULTS into an appropriate elisp value.
125 If the results look like a list or tuple, then convert them into an
126 Emacs-lisp table, otherwise return the results as a string."
127 (org-babel-script-escape results))
128
129 (defvar org-babel-python-buffers '((:default . nil)))
130
131 (defun org-babel-python-session-buffer (session)
132 "Return the buffer associated with SESSION."
133 (cdr (assoc session org-babel-python-buffers)))
134
135 (defvar py-default-interpreter)
136 (defun org-babel-python-initiate-session-by-key (&optional session)
137 "Initiate a python session.
138 If there is not a current inferior-process-buffer in SESSION
139 then create. Return the initialized session."
140 (require org-babel-python-mode)
141 (save-window-excursion
142 (let* ((session (if session (intern session) :default))
143 (python-buffer (org-babel-python-session-buffer session)))
144 (cond
145 ((and (eq 'python org-babel-python-mode)
146 (fboundp 'run-python)) ; python.el
147 (run-python))
148 ((and (eq 'python-mode org-babel-python-mode)
149 (fboundp 'py-shell)) ; python-mode.el
150 ;; Make sure that py-which-bufname is initialized, as otherwise
151 ;; it will be overwritten the first time a Python buffer is
152 ;; created.
153 (py-toggle-shells py-default-interpreter)
154 ;; `py-shell' creates a buffer whose name is the value of
155 ;; `py-which-bufname' with '*'s at the beginning and end
156 (let* ((bufname (if (and python-buffer (buffer-live-p python-buffer))
157 (replace-regexp-in-string ;; zap surrounding *
158 "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer)
159 (concat "Python-" (symbol-name session))))
160 (py-which-bufname bufname))
161 (py-shell)
162 (setq python-buffer (concat "*" bufname "*"))))
163 (t
164 (error "No function available for running an inferior python.")))
165 (setq org-babel-python-buffers
166 (cons (cons session python-buffer)
167 (assq-delete-all session org-babel-python-buffers)))
168 session)))
169
170 (defun org-babel-python-initiate-session (&optional session params)
171 "Create a session named SESSION according to PARAMS."
172 (unless (string= session "none")
173 (org-babel-python-session-buffer
174 (org-babel-python-initiate-session-by-key session))))
175
176 (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
177 "A string to indicate that evaluation has completed.")
178 (defvar org-babel-python-wrapper-method
179 "
180 def main():
181 %s
182
183 open('%s', 'w').write( str(main()) )")
184 (defvar org-babel-python-pp-wrapper-method
185 "
186 import pprint
187 def main():
188 %s
189
190 open('%s', 'w').write( pprint.pformat(main()) )")
191
192 (defun org-babel-python-evaluate
193 (session body &optional result-type result-params preamble)
194 "Evaluate BODY as python code."
195 (if session
196 (org-babel-python-evaluate-session
197 session body result-type result-params)
198 (org-babel-python-evaluate-external-process
199 body result-type result-params preamble)))
200
201 (defun org-babel-python-evaluate-external-process
202 (body &optional result-type result-params preamble)
203 "Evaluate BODY in external python process.
204 If RESULT-TYPE equals 'output then return standard output as a
205 string. If RESULT-TYPE equals 'value then return the value of the
206 last statement in BODY, as elisp."
207 ((lambda (raw)
208 (if (or (member "code" result-params)
209 (member "pp" result-params)
210 (and (member "output" result-params)
211 (not (member "table" result-params))))
212 raw
213 (org-babel-python-table-or-string (org-babel-trim raw))))
214 (case result-type
215 (output (org-babel-eval org-babel-python-command
216 (concat (if preamble (concat preamble "\n") "")
217 body)))
218 (value (let ((tmp-file (org-babel-temp-file "python-")))
219 (org-babel-eval
220 org-babel-python-command
221 (concat
222 (if preamble (concat preamble "\n") "")
223 (format
224 (if (member "pp" result-params)
225 org-babel-python-pp-wrapper-method
226 org-babel-python-wrapper-method)
227 (mapconcat
228 (lambda (line) (format "\t%s" line))
229 (split-string
230 (org-remove-indentation
231 (org-babel-trim body))
232 "[\r\n]") "\n")
233 (org-babel-process-file-name tmp-file 'noquote))))
234 (org-babel-eval-read-file tmp-file))))))
235
236 (defun org-babel-python-evaluate-session
237 (session body &optional result-type result-params)
238 "Pass BODY to the Python process in SESSION.
239 If RESULT-TYPE equals 'output then return standard output as a
240 string. If RESULT-TYPE equals 'value then return the value of the
241 last statement in BODY, as elisp."
242 (flet ((send-wait () (comint-send-input nil t) (sleep-for 0 5))
243 (dump-last-value
244 (tmp-file pp)
245 (mapc
246 (lambda (statement) (insert statement) (send-wait))
247 (if pp
248 (list
249 "import pprint"
250 (format "open('%s', 'w').write(pprint.pformat(_))"
251 (org-babel-process-file-name tmp-file 'noquote)))
252 (list (format "open('%s', 'w').write(str(_))"
253 (org-babel-process-file-name tmp-file 'noquote))))))
254 (input-body (body)
255 (mapc (lambda (line) (insert line) (send-wait))
256 (split-string body "[\r\n]"))
257 (send-wait)))
258 ((lambda (results)
259 (unless (string= (substring org-babel-python-eoe-indicator 1 -1) results)
260 (if (or (member "code" result-params)
261 (member "pp" result-params)
262 (and (member "output" result-params)
263 (not (member "table" result-params))))
264 results
265 (org-babel-python-table-or-string results))))
266 (case result-type
267 (output
268 (mapconcat
269 #'org-babel-trim
270 (butlast
271 (org-babel-comint-with-output
272 (session org-babel-python-eoe-indicator t body)
273 (input-body body)
274 (send-wait) (send-wait)
275 (insert org-babel-python-eoe-indicator)
276 (send-wait))
277 2) "\n"))
278 (value
279 (let ((tmp-file (org-babel-temp-file "python-")))
280 (org-babel-comint-with-output
281 (session org-babel-python-eoe-indicator nil body)
282 (let ((comint-process-echoes nil))
283 (input-body body)
284 (dump-last-value tmp-file (member "pp" result-params))
285 (send-wait) (send-wait)
286 (insert org-babel-python-eoe-indicator)
287 (send-wait)))
288 (org-babel-eval-read-file tmp-file)))))))
289
290 (defun org-babel-python-read-string (string)
291 "Strip 's from around python string"
292 (if (string-match "^'\\([^\000]+\\)'$" string)
293 (match-string 1 string)
294 string))
295
296 (provide 'ob-python)
297
298
299
300 ;;; ob-python.el ends here