org-protocol default template should be nil
[org-mode.git] / lisp / ob-python.el
bloba9684038070d18791e6d7907c56428561422d084
1 ;;; ob-python.el --- org-babel functions for python evaluation
3 ;; Copyright (C) 2009, 2010 Free Software Foundation
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.01trans
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 (defun org-babel-expand-body:python (body params &optional processed-params)
51 "Expand BODY according to PARAMS, return the expanded body."
52 (concat
53 (mapconcat ;; define any variables
54 (lambda (pair)
55 (format "%s=%s"
56 (car pair)
57 (org-babel-python-var-to-python (cdr pair))))
58 (nth 1 (or processed-params (org-babel-process-params params))) "\n")
59 "\n" (org-babel-trim body) "\n"))
61 (defun org-babel-execute:python (body params)
62 "Execute a block of Python code with Babel.
63 This function is called by `org-babel-execute-src-block'."
64 (let* ((processed-params (org-babel-process-params params))
65 (session (org-babel-python-initiate-session (first processed-params)))
66 (result-params (nth 2 processed-params))
67 (result-type (nth 3 processed-params))
68 (full-body (org-babel-expand-body:python
69 body params processed-params))
70 (result (org-babel-python-evaluate
71 session full-body result-type result-params)))
72 (or (cdr (assoc :file params))
73 (org-babel-reassemble-table
74 result
75 (org-babel-pick-name (nth 4 processed-params)
76 (cdr (assoc :colnames params)))
77 (org-babel-pick-name (nth 5 processed-params)
78 (cdr (assoc :rownames params)))))))
80 (defun org-babel-prep-session:python (session params)
81 "Prepare SESSION according to the header arguments in PARAMS."
82 (let* ((session (org-babel-python-initiate-session session))
83 (vars (org-babel-ref-variables params))
84 (var-lines (mapcar ;; define any variables
85 (lambda (pair)
86 (format "%s=%s"
87 (car pair)
88 (org-babel-python-var-to-python (cdr pair))))
89 vars)))
90 (org-babel-comint-in-buffer session
91 (mapc (lambda (var)
92 (end-of-line 1) (insert var) (comint-send-input)
93 (org-babel-comint-wait-for-output session)) var-lines))
94 session))
96 (defun org-babel-load-session:python (session body params)
97 "Load BODY into SESSION."
98 (save-window-excursion
99 (let ((buffer (org-babel-prep-session:python session params)))
100 (with-current-buffer buffer
101 (goto-char (process-mark (get-buffer-process (current-buffer))))
102 (insert (org-babel-chomp body)))
103 buffer)))
105 ;; helper functions
107 (defun org-babel-python-var-to-python (var)
108 "Convert an elisp value to a python variable.
109 Convert an elisp value, VAR, into a string of python source code
110 specifying a variable of the same value."
111 (if (listp var)
112 (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
113 (if (equal var 'hline)
114 "None"
115 (format
116 (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
117 var))))
119 (defun org-babel-python-table-or-string (results)
120 "Convert RESULTS into an appropriate elisp value.
121 If the results look like a list or tuple, then convert them into an
122 Emacs-lisp table, otherwise return the results as a string."
123 ((lambda (res)
124 (if (listp res)
125 (mapcar (lambda (el) (if (equal el 'None) 'hline el)) res)
126 res))
127 (org-babel-read
128 (if (and (stringp results) (string-match "^[([].+[])]$" results))
129 (org-babel-read
130 (concat "'"
131 (replace-regexp-in-string
132 "\\[" "(" (replace-regexp-in-string
133 "\\]" ")" (replace-regexp-in-string
134 ", " " " (replace-regexp-in-string
135 "'" "\"" results t))))))
136 results))))
138 (defvar org-babel-python-buffers '((:default . nil)))
140 (defun org-babel-python-session-buffer (session)
141 "Return the buffer associated with SESSION."
142 (cdr (assoc session org-babel-python-buffers)))
144 (defun org-babel-python-initiate-session-by-key (&optional session)
145 "Initiate a python session.
146 If there is not a current inferior-process-buffer in SESSION
147 then create. Return the initialized session."
148 (require org-babel-python-mode)
149 (save-window-excursion
150 (let* ((session (if session (intern session) :default))
151 (python-buffer (org-babel-python-session-buffer session)))
152 (cond
153 ((and (eq 'python org-babel-python-mode)
154 (fboundp 'run-python)) ; python.el
155 (run-python))
156 ((and (eq 'python-mode org-babel-python-mode)
157 (fboundp 'py-shell)) ; python-mode.el
158 ;; `py-shell' creates a buffer whose name is the value of
159 ;; `py-which-bufname' with '*'s at the beginning and end
160 (let* ((bufname (if python-buffer
161 (replace-regexp-in-string ;; zap surrounding *
162 "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer)
163 (concat "Python-" (symbol-name session))))
164 (py-which-bufname bufname))
165 (py-shell)
166 (setq python-buffer (concat "*" bufname "*"))))
168 (error "No function available for running an inferior python.")))
169 (setq org-babel-python-buffers
170 (cons (cons session python-buffer)
171 (assq-delete-all session org-babel-python-buffers)))
172 session)))
174 (defun org-babel-python-initiate-session (&optional session params)
175 "Create a session named SESSION according to PARAMS."
176 (unless (string= session "none")
177 (org-babel-python-session-buffer
178 (org-babel-python-initiate-session-by-key session))))
180 (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
181 "A string to indicate that evaluation has completed.")
182 (defvar org-babel-python-wrapper-method
184 def main():
187 open('%s', 'w').write( str(main()) )")
188 (defvar org-babel-python-pp-wrapper-method
190 import pprint
191 def main():
194 open('%s', 'w').write( pprint.pformat(main()) )")
196 (defun org-babel-python-evaluate
197 (buffer body &optional result-type result-params)
198 "Pass BODY to the Python process in BUFFER.
199 If RESULT-TYPE equals 'output then return a list of the outputs
200 of the statements in BODY, if RESULT-TYPE equals 'value then
201 return the value of the last statement in BODY, as elisp."
202 (if (not buffer)
203 ;; external process evaluation
204 (case result-type
205 (output (org-babel-eval org-babel-python-command body))
206 (value (let ((tmp-file (org-babel-temp-file "python-results-")))
207 (org-babel-eval org-babel-python-command
208 (format
209 (if (member "pp" result-params)
210 org-babel-python-pp-wrapper-method
211 org-babel-python-wrapper-method)
212 (mapconcat
213 (lambda (line) (format "\t%s" line))
214 (split-string
215 (org-remove-indentation
216 (org-babel-trim body))
217 "[\r\n]") "\n")
218 tmp-file))
219 ((lambda (raw)
220 (if (or (member "code" result-params)
221 (member "pp" result-params))
223 (org-babel-python-table-or-string raw)))
224 (org-babel-eval-read-file tmp-file)))))
225 ;; comint session evaluation
226 (flet ((dump-last-value (tmp-file pp)
227 (mapc
228 (lambda (statement) (insert statement) (comint-send-input))
229 (if pp
230 (list
231 "import pp"
232 (format "open('%s', 'w').write(pprint.pformat(_))" tmp-file))
233 (list (format "open('%s', 'w').write(str(_))" tmp-file)))))
234 (input-body (body)
235 (mapc (lambda (statement) (insert statement) (comint-send-input))
236 (split-string (org-babel-trim body) "[\r\n]+"))
237 (comint-send-input) (comint-send-input)))
238 (case result-type
239 (output
240 (mapconcat
241 #'org-babel-trim
242 (butlast
243 (org-babel-comint-with-output
244 (buffer org-babel-python-eoe-indicator t body)
245 (let ((comint-process-echoes nil))
246 (input-body body)
247 (insert org-babel-python-eoe-indicator)
248 (comint-send-input))) 2) "\n"))
249 (value
250 ((lambda (results)
251 (if (or (member "code" result-params) (member "pp" result-params))
252 results
253 (org-babel-python-table-or-string results)))
254 (let ((tmp-file (org-babel-temp-file "python-results-")))
255 (org-babel-comint-with-output
256 (buffer org-babel-python-eoe-indicator t body)
257 (let ((comint-process-echoes nil))
258 (input-body body)
259 (dump-last-value tmp-file (member "pp" result-params))
260 (comint-send-input) (comint-send-input)
261 (insert org-babel-python-eoe-indicator)
262 (comint-send-input)))
263 (org-babel-eval-read-file tmp-file))))))))
265 (defun org-babel-python-read-string (string)
266 "Strip 's from around python string"
267 (if (string-match "^'\\([^\000]+\\)'$" string)
268 (match-string 1 string)
269 string))
271 (provide 'ob-python)
273 ;; arch-tag: f19b6c3d-dfcb-4a1a-9ce0-45ade1ebc212
275 ;;; ob-python.el ends here