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