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
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 py-toggle-shells
"ext:python-mode" (arg))
39 (declare-function run-python
"ext:python" (&optional cmd noshow new
))
41 (add-to-list 'org-babel-tangle-lang-exts
'("python" .
"py"))
43 (defvar org-babel-default-header-args
:python
'())
45 (defvar org-babel-python-command
"python"
46 "Name of command for executing python code.")
48 (defvar org-babel-python-mode
(if (featurep 'xemacs
) 'python-mode
'python
)
49 "Preferred python mode for use in running python interactively.
50 This will typically be either 'python or 'python-mode.")
52 (defvar org-src-preserve-indentation
)
54 (defun org-babel-execute:python
(body params
)
55 "Execute a block of Python code with Babel.
56 This function is called by `org-babel-execute-src-block'."
57 (let* ((session (org-babel-python-initiate-session
58 (cdr (assoc :session params
))))
59 (result-params (cdr (assoc :result-params params
)))
60 (result-type (cdr (assoc :result-type params
)))
61 (return-val (when (and (eq result-type
'value
) (not session
))
62 (cdr (assoc :return params
))))
63 (preamble (cdr (assoc :preamble params
)))
65 (org-babel-expand-body:generic
66 (concat body
(if return-val
(format "return %s" return-val
) ""))
67 params
(org-babel-variable-assignments:python params
)))
68 (result (org-babel-python-evaluate
69 session full-body result-type result-params preamble
)))
70 (org-babel-reassemble-table
72 (org-babel-pick-name (cdr (assoc :colname-names params
))
73 (cdr (assoc :colnames params
)))
74 (org-babel-pick-name (cdr (assoc :rowname-names params
))
75 (cdr (assoc :rownames params
))))))
77 (defun org-babel-prep-session:python
(session params
)
78 "Prepare SESSION according to the header arguments in PARAMS.
79 VARS contains resolved variable references"
80 (let* ((session (org-babel-python-initiate-session session
))
82 (org-babel-variable-assignments:python params
)))
83 (org-babel-comint-in-buffer session
85 (end-of-line 1) (insert var
) (comint-send-input)
86 (org-babel-comint-wait-for-output session
)) var-lines
))
89 (defun org-babel-load-session:python
(session body params
)
90 "Load BODY into SESSION."
91 (save-window-excursion
92 (let ((buffer (org-babel-prep-session:python session params
)))
93 (with-current-buffer buffer
94 (goto-char (process-mark (get-buffer-process (current-buffer))))
95 (insert (org-babel-chomp body
)))
100 (defun org-babel-variable-assignments:python
(params)
101 "Return list of python statements assigning the block's variables"
106 (org-babel-python-var-to-python (cdr pair
))))
107 (mapcar #'cdr
(org-babel-get-header params
:var
))))
109 (defun org-babel-python-var-to-python (var)
110 "Convert an elisp value to a python variable.
111 Convert an elisp value, VAR, into a string of python source code
112 specifying a variable of the same value."
114 (concat "[" (mapconcat #'org-babel-python-var-to-python var
", ") "]")
115 (if (equal var
'hline
)
118 (if (and (stringp var
) (string-match "[\n\r]" var
)) "\"\"%S\"\"" "%S")
121 (defun org-babel-python-table-or-string (results)
122 "Convert RESULTS into an appropriate elisp value.
123 If the results look like a list or tuple, then convert them into an
124 Emacs-lisp table, otherwise return the results as a string."
125 (org-babel-script-escape results
))
127 (defvar org-babel-python-buffers
'((:default . nil
)))
129 (defun org-babel-python-session-buffer (session)
130 "Return the buffer associated with SESSION."
131 (cdr (assoc session org-babel-python-buffers
)))
133 (defvar py-default-interpreter
)
134 (defun org-babel-python-initiate-session-by-key (&optional session
)
135 "Initiate a python session.
136 If there is not a current inferior-process-buffer in SESSION
137 then create. Return the initialized session."
138 (require org-babel-python-mode
)
139 (save-window-excursion
140 (let* ((session (if session
(intern session
) :default
))
141 (python-buffer (org-babel-python-session-buffer session
)))
143 ((and (eq 'python org-babel-python-mode
)
144 (fboundp 'run-python
)) ; python.el
146 ((and (eq 'python-mode org-babel-python-mode
)
147 (fboundp 'py-shell
)) ; python-mode.el
148 ;; Make sure that py-which-bufname is initialized, as otherwise
149 ;; it will be overwritten the first time a Python buffer is
151 (py-toggle-shells py-default-interpreter
)
152 ;; `py-shell' creates a buffer whose name is the value of
153 ;; `py-which-bufname' with '*'s at the beginning and end
154 (let* ((bufname (if (and python-buffer
(buffer-live-p python-buffer
))
155 (replace-regexp-in-string ;; zap surrounding *
156 "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer
)
157 (concat "Python-" (symbol-name session
))))
158 (py-which-bufname bufname
))
160 (setq python-buffer
(concat "*" bufname
"*"))))
162 (error "No function available for running an inferior python.")))
163 (setq org-babel-python-buffers
164 (cons (cons session python-buffer
)
165 (assq-delete-all session org-babel-python-buffers
)))
168 (defun org-babel-python-initiate-session (&optional session params
)
169 "Create a session named SESSION according to PARAMS."
170 (unless (string= session
"none")
171 (org-babel-python-session-buffer
172 (org-babel-python-initiate-session-by-key session
))))
174 (defvar org-babel-python-eoe-indicator
"'org_babel_python_eoe'"
175 "A string to indicate that evaluation has completed.")
176 (defvar org-babel-python-wrapper-method
181 open('%s', 'w').write( str(main()) )")
182 (defvar org-babel-python-pp-wrapper-method
188 open('%s', 'w').write( pprint.pformat(main()) )")
190 (defun org-babel-python-evaluate
191 (session body
&optional result-type result-params preamble
)
192 "Evaluate BODY as python code."
194 (org-babel-python-evaluate-session
195 session body result-type result-params
)
196 (org-babel-python-evaluate-external-process
197 body result-type result-params preamble
)))
199 (defun org-babel-python-evaluate-external-process
200 (body &optional result-type result-params preamble
)
201 "Evaluate BODY in external python process.
202 If RESULT-TYPE equals 'output then return standard output as a
203 string. If RESULT-TYPE equals 'value then return the value of the
204 last statement in BODY, as elisp."
206 (if (or (member "code" result-params
)
207 (member "pp" result-params
)
208 (and (member "output" result-params
)
209 (not (member "table" result-params
))))
211 (org-babel-python-table-or-string (org-babel-trim raw
))))
213 (output (org-babel-eval org-babel-python-command
214 (concat (if preamble
(concat preamble
"\n") "")
216 (value (let ((tmp-file (org-babel-temp-file "python-")))
218 org-babel-python-command
220 (if preamble
(concat preamble
"\n") "")
222 (if (member "pp" result-params
)
223 org-babel-python-pp-wrapper-method
224 org-babel-python-wrapper-method
)
226 (lambda (line) (format "\t%s" line
))
228 (org-remove-indentation
229 (org-babel-trim body
))
231 (org-babel-process-file-name tmp-file
'noquote
))))
232 (org-babel-eval-read-file tmp-file
))))))
234 (defun org-babel-python-evaluate-session
235 (session body
&optional result-type result-params
)
236 "Pass BODY to the Python process in SESSION.
237 If RESULT-TYPE equals 'output then return standard output as a
238 string. If RESULT-TYPE equals 'value then return the value of the
239 last statement in BODY, as elisp."
240 (flet ((dump-last-value
243 (lambda (statement) (insert statement
) (comint-send-input))
247 (format "open('%s', 'w').write(pprint.pformat(_))"
248 (org-babel-process-file-name tmp-file
'noquote
)))
249 (list (format "open('%s', 'w').write(str(_))"
250 (org-babel-process-file-name tmp-file
'noquote
))))))
252 (mapc (lambda (statement) (insert statement
) (comint-send-input))
253 (split-string (org-babel-trim body
) "[\r\n]+"))
254 (comint-send-input) (comint-send-input)))
256 (if (or (member "code" result-params
)
257 (member "pp" result-params
)
258 (and (member "output" result-params
)
259 (not (member "table" result-params
))))
261 (org-babel-python-table-or-string results
)))
267 (org-babel-comint-with-output
268 (session org-babel-python-eoe-indicator t body
)
269 (let ((comint-process-echoes nil
))
271 (insert org-babel-python-eoe-indicator
)
272 (comint-send-input))) 2) "\n"))
274 (let ((tmp-file (org-babel-temp-file "python-")))
275 (org-babel-comint-with-output
276 (session org-babel-python-eoe-indicator nil body
)
277 (let ((comint-process-echoes nil
))
279 (dump-last-value tmp-file
(member "pp" result-params
))
280 (comint-send-input) (comint-send-input)
281 (insert org-babel-python-eoe-indicator
)
282 (comint-send-input)))
283 (org-babel-eval-read-file tmp-file
)))))))
285 (defun org-babel-python-read-string (string)
286 "Strip 's from around python string"
287 (if (string-match "^'\\([^\000]+\\)'$" string
)
288 (match-string 1 string
)
293 ;; arch-tag: f19b6c3d-dfcb-4a1a-9ce0-45ade1ebc212
295 ;;; ob-python.el ends here