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