1 ;;; ob-python.el --- org-babel functions for python evaluation
3 ;; Copyright (C) 2009-2015 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.
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."
46 :package-version
'(Org .
"8.0")
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."
56 :package-version
'(Org .
"8.0")
59 (defcustom org-babel-python-hline-to
"None"
60 "Replace hlines in incoming tables with this when translating to python."
63 :package-version
'(Org .
"8.0")
66 (defcustom org-babel-python-None-to
'hline
67 "Replace ‘None’ in python tables with this before returning."
70 :package-version
'(Org .
"8.0")
73 (defun org-babel-execute:python
(body params
)
74 "Execute a block of Python code with Babel.
75 This function is called by `org-babel-execute-src-block'."
76 (let* ((session (org-babel-python-initiate-session
77 (cdr (assoc :session params
))))
78 (result-params (cdr (assoc :result-params params
)))
79 (result-type (cdr (assoc :result-type params
)))
80 (return-val (when (and (eq result-type
'value
) (not session
))
81 (cdr (assoc :return params
))))
82 (preamble (cdr (assoc :preamble params
)))
84 (org-babel-expand-body:generic
85 (concat body
(if return-val
(format "\nreturn %s" return-val
) ""))
86 params
(org-babel-variable-assignments:python params
)))
87 (result (org-babel-python-evaluate
88 session full-body result-type result-params preamble
)))
89 (org-babel-reassemble-table
91 (org-babel-pick-name (cdr (assoc :colname-names params
))
92 (cdr (assoc :colnames params
)))
93 (org-babel-pick-name (cdr (assoc :rowname-names params
))
94 (cdr (assoc :rownames params
))))))
96 (defun org-babel-prep-session:python
(session params
)
97 "Prepare SESSION according to the header arguments in PARAMS.
98 VARS contains resolved variable references"
99 (let* ((session (org-babel-python-initiate-session session
))
101 (org-babel-variable-assignments:python params
)))
102 (org-babel-comint-in-buffer session
104 (end-of-line 1) (insert var
) (comint-send-input)
105 (org-babel-comint-wait-for-output session
)) var-lines
))
108 (defun org-babel-load-session:python
(session body params
)
109 "Load BODY into SESSION."
110 (save-window-excursion
111 (let ((buffer (org-babel-prep-session:python session params
)))
112 (with-current-buffer buffer
113 (goto-char (process-mark (get-buffer-process (current-buffer))))
114 (insert (org-babel-chomp body
)))
119 (defun org-babel-variable-assignments:python
(params)
120 "Return a list of Python statements assigning the block's variables."
125 (org-babel-python-var-to-python (cdr pair
))))
126 (mapcar #'cdr
(org-babel-get-header params
:var
))))
128 (defun org-babel-python-var-to-python (var)
129 "Convert an elisp value to a python variable.
130 Convert an elisp value, VAR, into a string of python source code
131 specifying a variable of the same value."
133 (concat "[" (mapconcat #'org-babel-python-var-to-python var
", ") "]")
134 (if (equal var
'hline
)
135 org-babel-python-hline-to
137 (if (and (stringp var
) (string-match "[\n\r]" var
)) "\"\"%S\"\"" "%S")
138 (if (stringp var
) (substring-no-properties var
) var
)))))
140 (defun org-babel-python-table-or-string (results)
141 "Convert RESULTS into an appropriate elisp value.
142 If the results look like a list or tuple, then convert them into an
143 Emacs-lisp table, otherwise return the results as a string."
144 (let ((res (org-babel-script-escape results
)))
146 (mapcar (lambda (el) (if (equal el
'None
)
147 org-babel-python-None-to el
))
151 (defvar org-babel-python-buffers
'((:default .
"*Python*")))
153 (defun org-babel-python-session-buffer (session)
154 "Return the buffer associated with SESSION."
155 (cdr (assoc session org-babel-python-buffers
)))
157 (defun org-babel-python-with-earmuffs (session)
158 (let ((name (if (stringp session
) session
(format "%s" session
))))
159 (if (and (string= "*" (substring name
0 1))
160 (string= "*" (substring name
(- (length name
) 1))))
162 (format "*%s*" name
))))
164 (defun org-babel-python-without-earmuffs (session)
165 (let ((name (if (stringp session
) session
(format "%s" session
))))
166 (if (and (string= "*" (substring name
0 1))
167 (string= "*" (substring name
(- (length name
) 1))))
168 (substring name
1 (- (length name
) 1))
171 (defvar py-default-interpreter
)
172 (defvar py-which-bufname
)
173 (defvar python-shell-buffer-name
)
174 (defun org-babel-python-initiate-session-by-key (&optional session
)
175 "Initiate a python session.
176 If there is not a current inferior-process-buffer in SESSION
177 then create. Return the initialized session."
178 (require org-babel-python-mode
)
179 (save-window-excursion
180 (let* ((session (if session
(intern session
) :default
))
181 (python-buffer (org-babel-python-session-buffer session
))
182 (cmd (if (member system-type
'(cygwin windows-nt ms-dos
))
183 (concat org-babel-python-command
" -i")
184 org-babel-python-command
)))
186 ((and (eq 'python org-babel-python-mode
)
187 (fboundp 'run-python
)) ; python.el
188 (if (not (version< "24.1" emacs-version
))
190 (unless python-buffer
191 (setq python-buffer
(org-babel-python-with-earmuffs session
)))
192 (let ((python-shell-buffer-name
193 (org-babel-python-without-earmuffs python-buffer
)))
195 ((and (eq 'python-mode org-babel-python-mode
)
196 (fboundp 'py-shell
)) ; python-mode.el
197 ;; Make sure that py-which-bufname is initialized, as otherwise
198 ;; it will be overwritten the first time a Python buffer is
200 (py-toggle-shells py-default-interpreter
)
201 ;; `py-shell' creates a buffer whose name is the value of
202 ;; `py-which-bufname' with '*'s at the beginning and end
203 (let* ((bufname (if (and python-buffer
(buffer-live-p python-buffer
))
204 (replace-regexp-in-string ;; zap surrounding *
205 "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer
)
206 (concat "Python-" (symbol-name session
))))
207 (py-which-bufname bufname
))
209 (setq python-buffer
(org-babel-python-with-earmuffs bufname
))))
211 (error "No function available for running an inferior Python")))
212 (setq org-babel-python-buffers
213 (cons (cons session python-buffer
)
214 (assq-delete-all session org-babel-python-buffers
)))
217 (defun org-babel-python-initiate-session (&optional session params
)
218 "Create a session named SESSION according to PARAMS."
219 (unless (string= session
"none")
220 (org-babel-python-session-buffer
221 (org-babel-python-initiate-session-by-key session
))))
223 (defvar org-babel-python-eoe-indicator
"'org_babel_python_eoe'"
224 "A string to indicate that evaluation has completed.")
225 (defvar org-babel-python-wrapper-method
230 open('%s', 'w').write( str(main()) )")
231 (defvar org-babel-python-pp-wrapper-method
237 open('%s', 'w').write( pprint.pformat(main()) )")
239 (defun org-babel-python-evaluate
240 (session body
&optional result-type result-params preamble
)
241 "Evaluate BODY as Python code."
243 (org-babel-python-evaluate-session
244 session body result-type result-params
)
245 (org-babel-python-evaluate-external-process
246 body result-type result-params preamble
)))
248 (defun org-babel-python-evaluate-external-process
249 (body &optional result-type result-params preamble
)
250 "Evaluate BODY in external python process.
251 If RESULT-TYPE equals 'output then return standard output as a
252 string. If RESULT-TYPE equals 'value then return the value of the
253 last statement in BODY, as elisp."
256 (output (org-babel-eval org-babel-python-command
257 (concat (if preamble
(concat preamble
"\n"))
259 (value (let ((tmp-file (org-babel-temp-file "python-")))
261 org-babel-python-command
263 (if preamble
(concat preamble
"\n") "")
265 (if (member "pp" result-params
)
266 org-babel-python-pp-wrapper-method
267 org-babel-python-wrapper-method
)
269 (lambda (line) (format "\t%s" line
))
271 (org-remove-indentation
272 (org-babel-trim body
))
274 (org-babel-process-file-name tmp-file
'noquote
))))
275 (org-babel-eval-read-file tmp-file
))))))
276 (org-babel-result-cond result-params
278 (org-babel-python-table-or-string (org-babel-trim raw
)))))
280 (defun org-babel-python-evaluate-session
281 (session body
&optional result-type result-params
)
282 "Pass BODY to the Python process in SESSION.
283 If RESULT-TYPE equals 'output then return standard output as a
284 string. If RESULT-TYPE equals 'value then return the value of the
285 last statement in BODY, as elisp."
286 (let* ((send-wait (lambda () (comint-send-input nil t
) (sleep-for 0 5)))
291 (lambda (statement) (insert statement
) (funcall send-wait
))
295 (format "open('%s', 'w').write(pprint.pformat(_))"
296 (org-babel-process-file-name tmp-file
'noquote
)))
297 (list (format "open('%s', 'w').write(str(_))"
298 (org-babel-process-file-name tmp-file
300 (input-body (lambda (body)
301 (mapc (lambda (line) (insert line
) (funcall send-wait
))
302 (split-string body
"[\r\n]"))
303 (funcall send-wait
)))
310 (org-babel-comint-with-output
311 (session org-babel-python-eoe-indicator t body
)
312 (funcall input-body body
)
313 (funcall send-wait
) (funcall send-wait
)
314 (insert org-babel-python-eoe-indicator
)
318 (let ((tmp-file (org-babel-temp-file "python-")))
319 (org-babel-comint-with-output
320 (session org-babel-python-eoe-indicator nil body
)
321 (let ((comint-process-echoes nil
))
322 (funcall input-body body
)
323 (funcall dump-last-value tmp-file
324 (member "pp" result-params
))
325 (funcall send-wait
) (funcall send-wait
)
326 (insert org-babel-python-eoe-indicator
)
327 (funcall send-wait
)))
328 (org-babel-eval-read-file tmp-file
))))))
329 (unless (string= (substring org-babel-python-eoe-indicator
1 -
1) results
)
330 (org-babel-result-cond result-params
332 (org-babel-python-table-or-string results
)))))
334 (defun org-babel-python-read-string (string)
335 "Strip 's from around Python string."
336 (if (string-match "^'\\([^\000]+\\)'$" string
)
337 (match-string 1 string
)
344 ;;; ob-python.el ends here