ox-html: Fix stack overflow in regexp matching
[org-mode.git] / lisp / ob-python.el
blobf2806c7472cb8f982e43721b9cdd8fdf1e4ede7f
1 ;;; ob-python.el --- org-babel functions for python evaluation
3 ;; Copyright (C) 2009-2013 Free Software Foundation, Inc.
5 ;; Authors: 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 (eval-when-compile (require 'cl))
33 (declare-function org-remove-indentation "org" )
34 (declare-function py-shell "ext:python-mode" (&optional argprompt))
35 (declare-function py-toggle-shells "ext:python-mode" (arg))
36 (declare-function run-python "ext:python" (&optional cmd noshow new))
38 (defvar org-babel-tangle-lang-exts)
39 (add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
41 (defvar org-babel-default-header-args:python '())
43 (defcustom org-babel-python-command "python"
44 "Name of the command for executing Python code."
45 :group 'org-babel
46 :version "24.3"
47 :type 'string)
49 (defcustom org-babel-python-mode
50 (if (or (featurep 'xemacs) (featurep 'python-mode)) 'python-mode 'python)
51 "Preferred python mode for use in running python interactively.
52 This will typically be either 'python or 'python-mode."
53 :group 'org-babel
54 :version "24.3"
55 :type 'function)
57 (defvar org-src-preserve-indentation)
59 (defcustom org-babel-python-hline-to "None"
60 "Replace hlines in incoming tables with this when translating to python."
61 :group 'org-babel
62 :type 'string)
64 (defcustom org-babel-python-None-to 'hline
65 "Replace 'None' in python tables with this before returning."
66 :group 'org-babel
67 :type 'string)
69 (defun org-babel-execute:python (body params)
70 "Execute a block of Python code with Babel.
71 This function is called by `org-babel-execute-src-block'."
72 (let* ((session (org-babel-python-initiate-session
73 (cdr (assoc :session params))))
74 (result-params (cdr (assoc :result-params params)))
75 (result-type (cdr (assoc :result-type params)))
76 (return-val (when (and (eq result-type 'value) (not session))
77 (cdr (assoc :return params))))
78 (preamble (cdr (assoc :preamble params)))
79 (full-body
80 (org-babel-expand-body:generic
81 (concat body (if return-val (format "\nreturn %s" return-val) ""))
82 params (org-babel-variable-assignments:python params)))
83 (result (org-babel-python-evaluate
84 session full-body result-type result-params preamble)))
85 (org-babel-reassemble-table
86 result
87 (org-babel-pick-name (cdr (assoc :colname-names params))
88 (cdr (assoc :colnames params)))
89 (org-babel-pick-name (cdr (assoc :rowname-names params))
90 (cdr (assoc :rownames params))))))
92 (defun org-babel-prep-session:python (session params)
93 "Prepare SESSION according to the header arguments in PARAMS.
94 VARS contains resolved variable references"
95 (let* ((session (org-babel-python-initiate-session session))
96 (var-lines
97 (org-babel-variable-assignments:python params)))
98 (org-babel-comint-in-buffer session
99 (mapc (lambda (var)
100 (end-of-line 1) (insert var) (comint-send-input)
101 (org-babel-comint-wait-for-output session)) var-lines))
102 session))
104 (defun org-babel-load-session:python (session body params)
105 "Load BODY into SESSION."
106 (save-window-excursion
107 (let ((buffer (org-babel-prep-session:python session params)))
108 (with-current-buffer buffer
109 (goto-char (process-mark (get-buffer-process (current-buffer))))
110 (insert (org-babel-chomp body)))
111 buffer)))
113 ;; helper functions
115 (defun org-babel-variable-assignments:python (params)
116 "Return a list of Python statements assigning the block's variables."
117 (mapcar
118 (lambda (pair)
119 (format "%s=%s"
120 (car pair)
121 (org-babel-python-var-to-python (cdr pair))))
122 (mapcar #'cdr (org-babel-get-header params :var))))
124 (defun org-babel-python-var-to-python (var)
125 "Convert an elisp value to a python variable.
126 Convert an elisp value, VAR, into a string of python source code
127 specifying a variable of the same value."
128 (if (listp var)
129 (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
130 (if (equal var 'hline)
131 org-babel-python-hline-to
132 (format
133 (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
134 var))))
136 (defun org-babel-python-table-or-string (results)
137 "Convert RESULTS into an appropriate elisp value.
138 If the results look like a list or tuple, then convert them into an
139 Emacs-lisp table, otherwise return the results as a string."
140 ((lambda (res)
141 (if (listp res)
142 (mapcar (lambda (el) (if (equal el 'None)
143 org-babel-python-None-to el))
144 res)
145 res))
146 (org-babel-script-escape results)))
148 (defvar org-babel-python-buffers '((:default . nil)))
150 (defun org-babel-python-session-buffer (session)
151 "Return the buffer associated with SESSION."
152 (cdr (assoc session org-babel-python-buffers)))
154 (defvar py-default-interpreter)
155 (defun org-babel-python-initiate-session-by-key (&optional session)
156 "Initiate a python session.
157 If there is not a current inferior-process-buffer in SESSION
158 then create. Return the initialized session."
159 (require org-babel-python-mode)
160 (save-window-excursion
161 (let* ((session (if session (intern session) :default))
162 (python-buffer (org-babel-python-session-buffer session)))
163 (cond
164 ((and (eq 'python org-babel-python-mode)
165 (fboundp 'run-python)) ; python.el
166 (if (version< "24.1" emacs-version)
167 (run-python org-babel-python-command)
168 (run-python)))
169 ((and (eq 'python-mode org-babel-python-mode)
170 (fboundp 'py-shell)) ; python-mode.el
171 ;; Make sure that py-which-bufname is initialized, as otherwise
172 ;; it will be overwritten the first time a Python buffer is
173 ;; created.
174 (py-toggle-shells py-default-interpreter)
175 ;; `py-shell' creates a buffer whose name is the value of
176 ;; `py-which-bufname' with '*'s at the beginning and end
177 (let* ((bufname (if (and python-buffer (buffer-live-p python-buffer))
178 (replace-regexp-in-string ;; zap surrounding *
179 "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer)
180 (concat "Python-" (symbol-name session))))
181 (py-which-bufname bufname))
182 (py-shell)
183 (setq python-buffer (concat "*" bufname "*"))))
185 (error "No function available for running an inferior Python")))
186 (setq org-babel-python-buffers
187 (cons (cons session python-buffer)
188 (assq-delete-all session org-babel-python-buffers)))
189 session)))
191 (defun org-babel-python-initiate-session (&optional session params)
192 "Create a session named SESSION according to PARAMS."
193 (unless (string= session "none")
194 (org-babel-python-session-buffer
195 (org-babel-python-initiate-session-by-key session))))
197 (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
198 "A string to indicate that evaluation has completed.")
199 (defvar org-babel-python-wrapper-method
201 def main():
204 open('%s', 'w').write( str(main()) )")
205 (defvar org-babel-python-pp-wrapper-method
207 import pprint
208 def main():
211 open('%s', 'w').write( pprint.pformat(main()) )")
213 (defun org-babel-python-evaluate
214 (session body &optional result-type result-params preamble)
215 "Evaluate BODY as Python code."
216 (if session
217 (org-babel-python-evaluate-session
218 session body result-type result-params)
219 (org-babel-python-evaluate-external-process
220 body result-type result-params preamble)))
222 (defun org-babel-python-evaluate-external-process
223 (body &optional result-type result-params preamble)
224 "Evaluate BODY in external python process.
225 If RESULT-TYPE equals 'output then return standard output as a
226 string. If RESULT-TYPE equals 'value then return the value of the
227 last statement in BODY, as elisp."
228 ((lambda (raw)
229 (org-babel-result-cond result-params
231 (org-babel-python-table-or-string (org-babel-trim raw))))
232 (case result-type
233 (output (org-babel-eval org-babel-python-command
234 (concat (if preamble (concat preamble "\n") "")
235 body)))
236 (value (let ((tmp-file (org-babel-temp-file "python-")))
237 (org-babel-eval
238 org-babel-python-command
239 (concat
240 (if preamble (concat preamble "\n") "")
241 (format
242 (if (member "pp" result-params)
243 org-babel-python-pp-wrapper-method
244 org-babel-python-wrapper-method)
245 (mapconcat
246 (lambda (line) (format "\t%s" line))
247 (split-string
248 (org-remove-indentation
249 (org-babel-trim body))
250 "[\r\n]") "\n")
251 (org-babel-process-file-name tmp-file 'noquote))))
252 (org-babel-eval-read-file tmp-file))))))
254 (defun org-babel-python-evaluate-session
255 (session body &optional result-type result-params)
256 "Pass BODY to the Python process in SESSION.
257 If RESULT-TYPE equals 'output then return standard output as a
258 string. If RESULT-TYPE equals 'value then return the value of the
259 last statement in BODY, as elisp."
260 (let* ((send-wait (lambda () (comint-send-input nil t) (sleep-for 0 5)))
261 (dump-last-value
262 (lambda
263 (tmp-file pp)
264 (mapc
265 (lambda (statement) (insert statement) (funcall send-wait))
266 (if pp
267 (list
268 "import pprint"
269 (format "open('%s', 'w').write(pprint.pformat(_))"
270 (org-babel-process-file-name tmp-file 'noquote)))
271 (list (format "open('%s', 'w').write(str(_))"
272 (org-babel-process-file-name tmp-file 'noquote)))))))
273 (input-body (lambda (body)
274 (mapc (lambda (line) (insert line) (funcall send-wait))
275 (split-string body "[\r\n]"))
276 (funcall send-wait))))
277 ((lambda (results)
278 (unless (string= (substring org-babel-python-eoe-indicator 1 -1) results)
279 (org-babel-result-cond result-params
280 results
281 (org-babel-python-table-or-string results))))
282 (case result-type
283 (output
284 (mapconcat
285 #'org-babel-trim
286 (butlast
287 (org-babel-comint-with-output
288 (session org-babel-python-eoe-indicator t body)
289 (funcall input-body body)
290 (funcall send-wait) (funcall send-wait)
291 (insert org-babel-python-eoe-indicator)
292 (funcall send-wait))
293 2) "\n"))
294 (value
295 (let ((tmp-file (org-babel-temp-file "python-")))
296 (org-babel-comint-with-output
297 (session org-babel-python-eoe-indicator nil body)
298 (let ((comint-process-echoes nil))
299 (funcall input-body body)
300 (funcall dump-last-value tmp-file (member "pp" result-params))
301 (funcall send-wait) (funcall send-wait)
302 (insert org-babel-python-eoe-indicator)
303 (funcall send-wait)))
304 (org-babel-eval-read-file tmp-file)))))))
306 (defun org-babel-python-read-string (string)
307 "Strip 's from around Python string."
308 (if (string-match "^'\\([^\000]+\\)'$" string)
309 (match-string 1 string)
310 string))
312 (provide 'ob-python)
316 ;;; ob-python.el ends here