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