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
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/>.
27 ;; Org-Babel support for evaluating python source code.
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
)))
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
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
))
81 (org-babel-variable-assignments:python params
)))
82 (org-babel-comint-in-buffer session
84 (end-of-line 1) (insert var
) (comint-send-input)
85 (org-babel-comint-wait-for-output session
)) var-lines
))
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
)))
99 (defun org-babel-variable-assignments:python
(params)
100 "Return list of python statements assigning the block's variables"
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."
113 (concat "[" (mapconcat #'org-babel-python-var-to-python var
", ") "]")
114 (if (equal var
'hline
)
117 (if (and (stringp var
) (string-match "[\n\r]" var
)) "\"\"%S\"\"" "%S")
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
)))
141 ((and (eq 'python org-babel-python-mode
)
142 (fboundp 'run-python
)) ; python.el
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
))
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
)))
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
175 open('%s', 'w').write( str(main()) )")
176 (defvar org-babel-python-pp-wrapper-method
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."
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."
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
205 (if preamble
(concat preamble
"\n") "")
207 (if (member "pp" result-params
)
208 org-babel-python-pp-wrapper-method
209 org-babel-python-wrapper-method
)
211 (lambda (line) (format "\t%s" line
))
213 (org-remove-indentation
214 (org-babel-trim body
))
216 (org-babel-process-file-name tmp-file
'noquote
))))
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
233 (lambda (statement) (insert statement
) (comint-send-input))
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
))))))
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)))
250 (org-babel-comint-with-output
251 (session org-babel-python-eoe-indicator t body
)
252 (let ((comint-process-echoes nil
))
254 (insert org-babel-python-eoe-indicator
)
255 (comint-send-input))) 2) "\n"))
258 (if (or (member "code" result-params
) (member "pp" result-params
))
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
))
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
)
281 ;;; ob-python.el ends here