1 ;;; ob-python.el --- org-babel functions for python evaluation
3 ;; Copyright (C) 2009-2011 Free Software Foundation
5 ;; Author: Eric Schulte
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
28 ;; Org-Babel support for evaluating python source code.
35 (eval-when-compile (require 'cl
))
37 (declare-function org-remove-indentation
"org" )
38 (declare-function py-shell
"ext:python-mode" (&optional argprompt
))
39 (declare-function py-toggle-shells
"ext:python-mode" (arg))
40 (declare-function run-python
"ext:python" (&optional cmd noshow new
))
42 (defvar org-babel-tangle-lang-exts
)
43 (add-to-list 'org-babel-tangle-lang-exts
'("python" .
"py"))
45 (defvar org-babel-default-header-args
:python
'())
47 (defvar org-babel-python-command
"python"
48 "Name of command for executing python code.")
50 (defvar org-babel-python-mode
(if (featurep 'xemacs
) 'python-mode
'python
)
51 "Preferred python mode for use in running python interactively.
52 This will typically be either 'python or 'python-mode.")
54 (defvar org-src-preserve-indentation
)
56 (defun org-babel-execute:python
(body params
)
57 "Execute a block of Python code with Babel.
58 This function is called by `org-babel-execute-src-block'."
59 (let* ((session (org-babel-python-initiate-session
60 (cdr (assoc :session params
))))
61 (result-params (cdr (assoc :result-params params
)))
62 (result-type (cdr (assoc :result-type params
)))
63 (return-val (when (and (eq result-type
'value
) (not session
))
64 (cdr (assoc :return params
))))
65 (preamble (cdr (assoc :preamble params
)))
67 (org-babel-expand-body:generic
68 (concat body
(if return-val
(format "return %s" return-val
) ""))
69 params
(org-babel-variable-assignments:python params
)))
70 (result (org-babel-python-evaluate
71 session full-body result-type result-params preamble
)))
72 (org-babel-reassemble-table
74 (org-babel-pick-name (cdr (assoc :colname-names params
))
75 (cdr (assoc :colnames params
)))
76 (org-babel-pick-name (cdr (assoc :rowname-names params
))
77 (cdr (assoc :rownames params
))))))
79 (defun org-babel-prep-session:python
(session params
)
80 "Prepare SESSION according to the header arguments in PARAMS.
81 VARS contains resolved variable references"
82 (let* ((session (org-babel-python-initiate-session session
))
84 (org-babel-variable-assignments:python params
)))
85 (org-babel-comint-in-buffer session
87 (end-of-line 1) (insert var
) (comint-send-input)
88 (org-babel-comint-wait-for-output session
)) var-lines
))
91 (defun org-babel-load-session:python
(session body params
)
92 "Load BODY into SESSION."
93 (save-window-excursion
94 (let ((buffer (org-babel-prep-session:python session params
)))
95 (with-current-buffer buffer
96 (goto-char (process-mark (get-buffer-process (current-buffer))))
97 (insert (org-babel-chomp body
)))
102 (defun org-babel-variable-assignments:python
(params)
103 "Return list of python statements assigning the block's variables"
108 (org-babel-python-var-to-python (cdr pair
))))
109 (mapcar #'cdr
(org-babel-get-header params
:var
))))
111 (defun org-babel-python-var-to-python (var)
112 "Convert an elisp value to a python variable.
113 Convert an elisp value, VAR, into a string of python source code
114 specifying a variable of the same value."
116 (concat "[" (mapconcat #'org-babel-python-var-to-python var
", ") "]")
117 (if (equal var
'hline
)
120 (if (and (stringp var
) (string-match "[\n\r]" var
)) "\"\"%S\"\"" "%S")
123 (defun org-babel-python-table-or-string (results)
124 "Convert RESULTS into an appropriate elisp value.
125 If the results look like a list or tuple, then convert them into an
126 Emacs-lisp table, otherwise return the results as a string."
127 (org-babel-script-escape results
))
129 (defvar org-babel-python-buffers
'((:default . nil
)))
131 (defun org-babel-python-session-buffer (session)
132 "Return the buffer associated with SESSION."
133 (cdr (assoc session org-babel-python-buffers
)))
135 (defvar py-default-interpreter
)
136 (defun org-babel-python-initiate-session-by-key (&optional session
)
137 "Initiate a python session.
138 If there is not a current inferior-process-buffer in SESSION
139 then create. Return the initialized session."
140 (require org-babel-python-mode
)
141 (save-window-excursion
142 (let* ((session (if session
(intern session
) :default
))
143 (python-buffer (org-babel-python-session-buffer session
)))
145 ((and (eq 'python org-babel-python-mode
)
146 (fboundp 'run-python
)) ; python.el
148 ((and (eq 'python-mode org-babel-python-mode
)
149 (fboundp 'py-shell
)) ; python-mode.el
150 ;; Make sure that py-which-bufname is initialized, as otherwise
151 ;; it will be overwritten the first time a Python buffer is
153 (py-toggle-shells py-default-interpreter
)
154 ;; `py-shell' creates a buffer whose name is the value of
155 ;; `py-which-bufname' with '*'s at the beginning and end
156 (let* ((bufname (if (and python-buffer
(buffer-live-p python-buffer
))
157 (replace-regexp-in-string ;; zap surrounding *
158 "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer
)
159 (concat "Python-" (symbol-name session
))))
160 (py-which-bufname bufname
))
162 (setq python-buffer
(concat "*" bufname
"*"))))
164 (error "No function available for running an inferior python.")))
165 (setq org-babel-python-buffers
166 (cons (cons session python-buffer
)
167 (assq-delete-all session org-babel-python-buffers
)))
170 (defun org-babel-python-initiate-session (&optional session params
)
171 "Create a session named SESSION according to PARAMS."
172 (unless (string= session
"none")
173 (org-babel-python-session-buffer
174 (org-babel-python-initiate-session-by-key session
))))
176 (defvar org-babel-python-eoe-indicator
"'org_babel_python_eoe'"
177 "A string to indicate that evaluation has completed.")
178 (defvar org-babel-python-wrapper-method
183 open('%s', 'w').write( str(main()) )")
184 (defvar org-babel-python-pp-wrapper-method
190 open('%s', 'w').write( pprint.pformat(main()) )")
192 (defun org-babel-python-evaluate
193 (session body
&optional result-type result-params preamble
)
194 "Evaluate BODY as python code."
196 (org-babel-python-evaluate-session
197 session body result-type result-params
)
198 (org-babel-python-evaluate-external-process
199 body result-type result-params preamble
)))
201 (defun org-babel-python-evaluate-external-process
202 (body &optional result-type result-params preamble
)
203 "Evaluate BODY in external python process.
204 If RESULT-TYPE equals 'output then return standard output as a
205 string. If RESULT-TYPE equals 'value then return the value of the
206 last statement in BODY, as elisp."
208 (if (or (member "code" result-params
)
209 (member "pp" result-params
)
210 (and (member "output" result-params
)
211 (not (member "table" result-params
))))
213 (org-babel-python-table-or-string (org-babel-trim raw
))))
215 (output (org-babel-eval org-babel-python-command
216 (concat (if preamble
(concat preamble
"\n") "")
218 (value (let ((tmp-file (org-babel-temp-file "python-")))
220 org-babel-python-command
222 (if preamble
(concat preamble
"\n") "")
224 (if (member "pp" result-params
)
225 org-babel-python-pp-wrapper-method
226 org-babel-python-wrapper-method
)
228 (lambda (line) (format "\t%s" line
))
230 (org-remove-indentation
231 (org-babel-trim body
))
233 (org-babel-process-file-name tmp-file
'noquote
))))
234 (org-babel-eval-read-file tmp-file
))))))
236 (defun org-babel-python-evaluate-session
237 (session body
&optional result-type result-params
)
238 "Pass BODY to the Python process in SESSION.
239 If RESULT-TYPE equals 'output then return standard output as a
240 string. If RESULT-TYPE equals 'value then return the value of the
241 last statement in BODY, as elisp."
242 (flet ((send-wait () (comint-send-input nil t
) (sleep-for 0 5))
246 (lambda (statement) (insert statement
) (send-wait))
250 (format "open('%s', 'w').write(pprint.pformat(_))"
251 (org-babel-process-file-name tmp-file
'noquote
)))
252 (list (format "open('%s', 'w').write(str(_))"
253 (org-babel-process-file-name tmp-file
'noquote
))))))
255 (mapc (lambda (line) (insert line
) (send-wait))
256 (split-string body
"[\r\n]"))
259 (unless (string= (substring org-babel-python-eoe-indicator
1 -
1) results
)
260 (if (or (member "code" result-params
)
261 (member "pp" result-params
)
262 (and (member "output" result-params
)
263 (not (member "table" result-params
))))
265 (org-babel-python-table-or-string results
))))
271 (org-babel-comint-with-output
272 (session org-babel-python-eoe-indicator t body
)
274 (send-wait) (send-wait)
275 (insert org-babel-python-eoe-indicator
)
279 (let ((tmp-file (org-babel-temp-file "python-")))
280 (org-babel-comint-with-output
281 (session org-babel-python-eoe-indicator nil body
)
282 (let ((comint-process-echoes nil
))
284 (dump-last-value tmp-file
(member "pp" result-params
))
285 (send-wait) (send-wait)
286 (insert org-babel-python-eoe-indicator
)
288 (org-babel-eval-read-file tmp-file
)))))))
290 (defun org-babel-python-read-string (string)
291 "Strip 's from around python string"
292 (if (string-match "^'\\([^\000]+\\)'$" string
)
293 (match-string 1 string
)
300 ;;; ob-python.el ends here