1 ;;; ob-python.el --- org-babel functions for python evaluation
3 ;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
5 ;; Authors: Eric Schulte
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/>.
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 (defvar org-babel-tangle-lang-exts
)
42 (add-to-list 'org-babel-tangle-lang-exts
'("python" .
"py"))
44 (defvar org-babel-default-header-args
:python
'())
46 (defvar org-babel-python-command
"python"
47 "Name of command for executing Python code.")
49 (defvar org-babel-python-mode
(if (featurep 'xemacs
) 'python-mode
'python
)
50 "Preferred python mode for use in running python interactively.
51 This will typically be either 'python or 'python-mode.")
53 (defvar org-src-preserve-indentation
)
55 (defcustom org-babel-python-hline-to
"None"
56 "Replace hlines in incoming tables with this when translating to python.")
58 (defcustom org-babel-python-None-to
'hline
59 "Replace 'None' in python tables with this before returning.")
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* ((session (org-babel-python-initiate-session
65 (cdr (assoc :session params
))))
66 (result-params (cdr (assoc :result-params params
)))
67 (result-type (cdr (assoc :result-type params
)))
68 (return-val (when (and (eq result-type
'value
) (not session
))
69 (cdr (assoc :return params
))))
70 (preamble (cdr (assoc :preamble params
)))
72 (org-babel-expand-body:generic
73 (concat body
(if return-val
(format "\nreturn %s" return-val
) ""))
74 params
(org-babel-variable-assignments:python params
)))
75 (result (org-babel-python-evaluate
76 session full-body result-type result-params preamble
)))
77 (org-babel-reassemble-table
79 (org-babel-pick-name (cdr (assoc :colname-names params
))
80 (cdr (assoc :colnames params
)))
81 (org-babel-pick-name (cdr (assoc :rowname-names params
))
82 (cdr (assoc :rownames params
))))))
84 (defun org-babel-prep-session:python
(session params
)
85 "Prepare SESSION according to the header arguments in PARAMS.
86 VARS contains resolved variable references"
87 (let* ((session (org-babel-python-initiate-session session
))
89 (org-babel-variable-assignments:python params
)))
90 (org-babel-comint-in-buffer session
92 (end-of-line 1) (insert var
) (comint-send-input)
93 (org-babel-comint-wait-for-output session
)) var-lines
))
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
)))
107 (defun org-babel-variable-assignments:python
(params)
108 "Return a list of Python statements assigning the block's variables."
113 (org-babel-python-var-to-python (cdr pair
))))
114 (mapcar #'cdr
(org-babel-get-header params
:var
))))
116 (defun org-babel-python-var-to-python (var)
117 "Convert an elisp value to a python variable.
118 Convert an elisp value, VAR, into a string of python source code
119 specifying a variable of the same value."
121 (concat "[" (mapconcat #'org-babel-python-var-to-python var
", ") "]")
122 (if (equal var
'hline
)
123 org-babel-python-hline-to
125 (if (and (stringp var
) (string-match "[\n\r]" var
)) "\"\"%S\"\"" "%S")
128 (defun org-babel-python-table-or-string (results)
129 "Convert RESULTS into an appropriate elisp value.
130 If the results look like a list or tuple, then convert them into an
131 Emacs-lisp table, otherwise return the results as a string."
134 (mapcar (lambda (el) (if (equal el
'None
)
135 org-babel-python-None-to el
))
138 (org-babel-script-escape results
)))
140 (defvar org-babel-python-buffers
'((:default . nil
)))
142 (defun org-babel-python-session-buffer (session)
143 "Return the buffer associated with SESSION."
144 (cdr (assoc session org-babel-python-buffers
)))
146 (defvar py-default-interpreter
)
147 (defun org-babel-python-initiate-session-by-key (&optional session
)
148 "Initiate a python session.
149 If there is not a current inferior-process-buffer in SESSION
150 then create. Return the initialized session."
151 (require org-babel-python-mode
)
152 (save-window-excursion
153 (let* ((session (if session
(intern session
) :default
))
154 (python-buffer (org-babel-python-session-buffer session
)))
156 ((and (eq 'python org-babel-python-mode
)
157 (fboundp 'run-python
)) ; python.el
159 ((and (eq 'python-mode org-babel-python-mode
)
160 (fboundp 'py-shell
)) ; python-mode.el
161 ;; Make sure that py-which-bufname is initialized, as otherwise
162 ;; it will be overwritten the first time a Python buffer is
164 (py-toggle-shells py-default-interpreter
)
165 ;; `py-shell' creates a buffer whose name is the value of
166 ;; `py-which-bufname' with '*'s at the beginning and end
167 (let* ((bufname (if (and python-buffer
(buffer-live-p python-buffer
))
168 (replace-regexp-in-string ;; zap surrounding *
169 "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer
)
170 (concat "Python-" (symbol-name session
))))
171 (py-which-bufname bufname
))
173 (setq python-buffer
(concat "*" bufname
"*"))))
175 (error "No function available for running an inferior Python")))
176 (setq org-babel-python-buffers
177 (cons (cons session python-buffer
)
178 (assq-delete-all session org-babel-python-buffers
)))
181 (defun org-babel-python-initiate-session (&optional session params
)
182 "Create a session named SESSION according to PARAMS."
183 (unless (string= session
"none")
184 (org-babel-python-session-buffer
185 (org-babel-python-initiate-session-by-key session
))))
187 (defvar org-babel-python-eoe-indicator
"'org_babel_python_eoe'"
188 "A string to indicate that evaluation has completed.")
189 (defvar org-babel-python-wrapper-method
194 open('%s', 'w').write( str(main()) )")
195 (defvar org-babel-python-pp-wrapper-method
201 open('%s', 'w').write( pprint.pformat(main()) )")
203 (defun org-babel-python-evaluate
204 (session body
&optional result-type result-params preamble
)
205 "Evaluate BODY as Python code."
207 (org-babel-python-evaluate-session
208 session body result-type result-params
)
209 (org-babel-python-evaluate-external-process
210 body result-type result-params preamble
)))
212 (defun org-babel-python-evaluate-external-process
213 (body &optional result-type result-params preamble
)
214 "Evaluate BODY in external python process.
215 If RESULT-TYPE equals 'output then return standard output as a
216 string. If RESULT-TYPE equals 'value then return the value of the
217 last statement in BODY, as elisp."
219 (if (or (member "code" result-params
)
220 (member "pp" result-params
)
221 (and (member "output" result-params
)
222 (not (member "table" result-params
))))
224 (org-babel-python-table-or-string (org-babel-trim raw
))))
226 (output (org-babel-eval org-babel-python-command
227 (concat (if preamble
(concat preamble
"\n") "")
229 (value (let ((tmp-file (org-babel-temp-file "python-")))
231 org-babel-python-command
233 (if preamble
(concat preamble
"\n") "")
235 (if (member "pp" result-params
)
236 org-babel-python-pp-wrapper-method
237 org-babel-python-wrapper-method
)
239 (lambda (line) (format "\t%s" line
))
241 (org-remove-indentation
242 (org-babel-trim body
))
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)))
258 (lambda (statement) (insert statement
) (funcall send-wait
))
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
))))
271 (unless (string= (substring org-babel-python-eoe-indicator
1 -
1) results
)
272 (if (or (member "code" result-params
)
273 (member "pp" result-params
)
274 (and (member "output" result-params
)
275 (not (member "table" result-params
))))
277 (org-babel-python-table-or-string results
))))
283 (org-babel-comint-with-output
284 (session org-babel-python-eoe-indicator t body
)
285 (funcall input-body body
)
286 (funcall send-wait
) (funcall send-wait
)
287 (insert org-babel-python-eoe-indicator
)
291 (let ((tmp-file (org-babel-temp-file "python-")))
292 (org-babel-comint-with-output
293 (session org-babel-python-eoe-indicator nil body
)
294 (let ((comint-process-echoes nil
))
295 (funcall input-body body
)
296 (funcall dump-last-value tmp-file
(member "pp" result-params
))
297 (funcall send-wait
) (funcall send-wait
)
298 (insert org-babel-python-eoe-indicator
)
299 (funcall send-wait
)))
300 (org-babel-eval-read-file tmp-file
)))))))
302 (defun org-babel-python-read-string (string)
303 "Strip 's from around Python string."
304 (if (string-match "^'\\([^\000]+\\)'$" string
)
305 (match-string 1 string
)
312 ;;; ob-python.el ends here