* admin/notes/copyright: Remove comments about deleted files in src/{m,s}.
[emacs.git] / lisp / org / ob-python.el
blobb53513a212c19613b9bcd523ae0bcae18ffec4f2
1 ;;; ob-python.el --- org-babel functions for python evaluation
3 ;; Copyright (C) 2009-2011 Free Software Foundation
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.4
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 run-python "ext:python" (&optional cmd noshow new))
40 (add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
42 (defvar org-babel-default-header-args:python '())
44 (defvar org-babel-python-command "python"
45 "Name of command for executing python code.")
47 (defvar org-babel-python-mode (if (featurep 'xemacs) 'python-mode 'python)
48 "Preferred python mode for use in running python interactively.")
50 (defvar org-src-preserve-indentation)
52 (defun org-babel-execute:python (body params)
53 "Execute a block of Python code with Babel.
54 This function is called by `org-babel-execute-src-block'."
55 (let* ((session (org-babel-python-initiate-session
56 (cdr (assoc :session params))))
57 (result-params (cdr (assoc :result-params params)))
58 (result-type (cdr (assoc :result-type params)))
59 (return-val (when (and (eq result-type 'value) (not session))
60 (cdr (assoc :return params))))
61 (preamble (cdr (assoc :preamble params)))
62 (full-body
63 (org-babel-expand-body:generic
64 (concat body (if return-val (format "return %s" return-val) ""))
65 params (org-babel-variable-assignments:python params)))
66 (result (org-babel-python-evaluate
67 session full-body result-type result-params preamble)))
68 (or (cdr (assoc :file params))
69 (org-babel-reassemble-table
70 result
71 (org-babel-pick-name (cdr (assoc :colname-names params))
72 (cdr (assoc :colnames params)))
73 (org-babel-pick-name (cdr (assoc :rowname-names params))
74 (cdr (assoc :rownames params)))))))
76 (defun org-babel-prep-session:python (session params)
77 "Prepare SESSION according to the header arguments in PARAMS.
78 VARS contains resolved variable references"
79 (let* ((session (org-babel-python-initiate-session session))
80 (var-lines
81 (org-babel-variable-assignments:python params)))
82 (org-babel-comint-in-buffer session
83 (mapc (lambda (var)
84 (end-of-line 1) (insert var) (comint-send-input)
85 (org-babel-comint-wait-for-output session)) var-lines))
86 session))
88 (defun org-babel-load-session:python (session body params)
89 "Load BODY into SESSION."
90 (save-window-excursion
91 (let ((buffer (org-babel-prep-session:python session params)))
92 (with-current-buffer buffer
93 (goto-char (process-mark (get-buffer-process (current-buffer))))
94 (insert (org-babel-chomp body)))
95 buffer)))
97 ;; helper functions
99 (defun org-babel-variable-assignments:python (params)
100 "Return list of python statements assigning the block's variables"
101 (mapcar
102 (lambda (pair)
103 (format "%s=%s"
104 (car pair)
105 (org-babel-python-var-to-python (cdr pair))))
106 (mapcar #'cdr (org-babel-get-header params :var))))
108 (defun org-babel-python-var-to-python (var)
109 "Convert an elisp value to a python variable.
110 Convert an elisp value, VAR, into a string of python source code
111 specifying a variable of the same value."
112 (if (listp var)
113 (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
114 (if (equal var 'hline)
115 "None"
116 (format
117 (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
118 var))))
120 (defun org-babel-python-table-or-string (results)
121 "Convert RESULTS into an appropriate elisp value.
122 If the results look like a list or tuple, then convert them into an
123 Emacs-lisp table, otherwise return the results as a string."
124 (org-babel-script-escape results))
126 (defvar org-babel-python-buffers '((:default . nil)))
128 (defun org-babel-python-session-buffer (session)
129 "Return the buffer associated with SESSION."
130 (cdr (assoc session org-babel-python-buffers)))
132 (defun org-babel-python-initiate-session-by-key (&optional session)
133 "Initiate a python session.
134 If there is not a current inferior-process-buffer in SESSION
135 then create. Return the initialized session."
136 (require org-babel-python-mode)
137 (save-window-excursion
138 (let* ((session (if session (intern session) :default))
139 (python-buffer (org-babel-python-session-buffer session)))
140 (cond
141 ((and (eq 'python org-babel-python-mode)
142 (fboundp 'run-python)) ; python.el
143 (run-python))
144 ((and (eq 'python-mode org-babel-python-mode)
145 (fboundp 'py-shell)) ; python-mode.el
146 ;; `py-shell' creates a buffer whose name is the value of
147 ;; `py-which-bufname' with '*'s at the beginning and end
148 (let* ((bufname (if python-buffer
149 (replace-regexp-in-string ;; zap surrounding *
150 "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer)
151 (concat "Python-" (symbol-name session))))
152 (py-which-bufname bufname))
153 (py-shell)
154 (setq python-buffer (concat "*" bufname "*"))))
156 (error "No function available for running an inferior python.")))
157 (setq org-babel-python-buffers
158 (cons (cons session python-buffer)
159 (assq-delete-all session org-babel-python-buffers)))
160 session)))
162 (defun org-babel-python-initiate-session (&optional session params)
163 "Create a session named SESSION according to PARAMS."
164 (unless (string= session "none")
165 (org-babel-python-session-buffer
166 (org-babel-python-initiate-session-by-key session))))
168 (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
169 "A string to indicate that evaluation has completed.")
170 (defvar org-babel-python-wrapper-method
172 def main():
175 open('%s', 'w').write( str(main()) )")
176 (defvar org-babel-python-pp-wrapper-method
178 import pprint
179 def main():
182 open('%s', 'w').write( pprint.pformat(main()) )")
184 (defun org-babel-python-evaluate
185 (session body &optional result-type result-params preamble)
186 "Evaluate BODY as python code."
187 (if session
188 (org-babel-python-evaluate-session
189 session body result-type result-params)
190 (org-babel-python-evaluate-external-process
191 body result-type result-params preamble)))
193 (defun org-babel-python-evaluate-external-process
194 (body &optional result-type result-params preamble)
195 "Evaluate BODY in external python process.
196 If RESULT-TYPE equals 'output then return standard output as a
197 string. If RESULT-TYPE equals 'value then return the value of the
198 last statement in BODY, as elisp."
199 (case result-type
200 (output (org-babel-eval org-babel-python-command
201 (concat (if preamble (concat preamble "\n") "") body)))
202 (value (let ((tmp-file (org-babel-temp-file "python-")))
203 (org-babel-eval org-babel-python-command
204 (concat
205 (if preamble (concat preamble "\n") "")
206 (format
207 (if (member "pp" result-params)
208 org-babel-python-pp-wrapper-method
209 org-babel-python-wrapper-method)
210 (mapconcat
211 (lambda (line) (format "\t%s" line))
212 (split-string
213 (org-remove-indentation
214 (org-babel-trim body))
215 "[\r\n]") "\n")
216 (org-babel-process-file-name tmp-file 'noquote))))
217 ((lambda (raw)
218 (if (or (member "code" result-params)
219 (member "pp" result-params))
221 (org-babel-python-table-or-string raw)))
222 (org-babel-eval-read-file tmp-file))))))
224 (defun org-babel-python-evaluate-session
225 (session body &optional result-type result-params)
226 "Pass BODY to the Python process in SESSION.
227 If RESULT-TYPE equals 'output then return standard output as a
228 string. If RESULT-TYPE equals 'value then return the value of the
229 last statement in BODY, as elisp."
230 (flet ((dump-last-value
231 (tmp-file pp)
232 (mapc
233 (lambda (statement) (insert statement) (comint-send-input))
234 (if pp
235 (list
236 "import pprint"
237 (format "open('%s', 'w').write(pprint.pformat(_))"
238 (org-babel-process-file-name tmp-file 'noquote)))
239 (list (format "open('%s', 'w').write(str(_))"
240 (org-babel-process-file-name tmp-file 'noquote))))))
241 (input-body (body)
242 (mapc (lambda (statement) (insert statement) (comint-send-input))
243 (split-string (org-babel-trim body) "[\r\n]+"))
244 (comint-send-input) (comint-send-input)))
245 (case result-type
246 (output
247 (mapconcat
248 #'org-babel-trim
249 (butlast
250 (org-babel-comint-with-output
251 (session org-babel-python-eoe-indicator t body)
252 (let ((comint-process-echoes nil))
253 (input-body body)
254 (insert org-babel-python-eoe-indicator)
255 (comint-send-input))) 2) "\n"))
256 (value
257 ((lambda (results)
258 (if (or (member "code" result-params) (member "pp" result-params))
259 results
260 (org-babel-python-table-or-string results)))
261 (let ((tmp-file (org-babel-temp-file "python-")))
262 (org-babel-comint-with-output
263 (session org-babel-python-eoe-indicator t body)
264 (let ((comint-process-echoes nil))
265 (input-body body)
266 (dump-last-value tmp-file (member "pp" result-params))
267 (comint-send-input) (comint-send-input)
268 (insert org-babel-python-eoe-indicator)
269 (comint-send-input)))
270 (org-babel-eval-read-file tmp-file)))))))
272 (defun org-babel-python-read-string (string)
273 "Strip 's from around python string"
274 (if (string-match "^'\\([^\000]+\\)'$" string)
275 (match-string 1 string)
276 string))
278 (provide 'ob-python)
281 ;;; ob-python.el ends here