lisp/org-table.el: fix table alignment
[org-mode/org-tableheadings.git] / lisp / ob-python.el
blobd4ee230e49266946a187c51b6b4e45a8c0f874f0
1 ;;; ob-python.el --- Babel Functions for Python -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2019 Free Software Foundation, Inc.
5 ;; Authors: Eric Schulte
6 ;; Dan Davison
7 ;; Keywords: literate programming, reproducible research
8 ;; Homepage: https://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 <https://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Org-Babel support for evaluating python source code.
29 ;;; Code:
30 (require 'ob)
31 (require 'org-macs)
33 (declare-function py-shell "ext:python-mode" (&optional argprompt))
34 (declare-function py-toggle-shells "ext:python-mode" (arg))
35 (declare-function run-python "ext:python" (&optional cmd dedicated show))
37 (defvar org-babel-tangle-lang-exts)
38 (add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
40 (defvar org-babel-default-header-args:python '())
42 (defcustom org-babel-python-command "python"
43 "Name of the command for executing Python code."
44 :version "24.4"
45 :package-version '(Org . "8.0")
46 :group 'org-babel
47 :type 'string)
49 (defcustom org-babel-python-mode
50 (if (featurep 'python-mode) 'python-mode 'python)
51 "Preferred python mode for use in running python interactively.
52 This will typically be either `python' or `python-mode'."
53 :group 'org-babel
54 :version "24.4"
55 :package-version '(Org . "8.0")
56 :type 'symbol)
58 (defcustom org-babel-python-hline-to "None"
59 "Replace hlines in incoming tables with this when translating to python."
60 :group 'org-babel
61 :version "24.4"
62 :package-version '(Org . "8.0")
63 :type 'string)
65 (defcustom org-babel-python-None-to 'hline
66 "Replace `None' in python tables with this before returning."
67 :group 'org-babel
68 :version "24.4"
69 :package-version '(Org . "8.0")
70 :type 'symbol)
72 (defun org-babel-execute:python (body params)
73 "Execute a block of Python code with Babel.
74 This function is called by `org-babel-execute-src-block'."
75 (let* ((org-babel-python-command
76 (or (cdr (assq :python params))
77 org-babel-python-command))
78 (session (org-babel-python-initiate-session
79 (cdr (assq :session params))))
80 (result-params (cdr (assq :result-params params)))
81 (result-type (cdr (assq :result-type params)))
82 (return-val (when (and (eq result-type 'value) (not session))
83 (cdr (assq :return params))))
84 (preamble (cdr (assq :preamble params)))
85 (full-body
86 (org-babel-expand-body:generic
87 (concat body (if return-val (format "\nreturn %s" return-val) ""))
88 params (org-babel-variable-assignments:python params)))
89 (result (org-babel-python-evaluate
90 session full-body result-type result-params preamble)))
91 (org-babel-reassemble-table
92 result
93 (org-babel-pick-name (cdr (assq :colname-names params))
94 (cdr (assq :colnames params)))
95 (org-babel-pick-name (cdr (assq :rowname-names params))
96 (cdr (assq :rownames params))))))
98 (defun org-babel-prep-session:python (session params)
99 "Prepare SESSION according to the header arguments in PARAMS.
100 VARS contains resolved variable references"
101 (let* ((session (org-babel-python-initiate-session session))
102 (var-lines
103 (org-babel-variable-assignments:python params)))
104 (org-babel-comint-in-buffer session
105 (mapc (lambda (var)
106 (end-of-line 1) (insert var) (comint-send-input)
107 (org-babel-comint-wait-for-output session)) var-lines))
108 session))
110 (defun org-babel-load-session:python (session body params)
111 "Load BODY into SESSION."
112 (save-window-excursion
113 (let ((buffer (org-babel-prep-session:python session params)))
114 (with-current-buffer buffer
115 (goto-char (process-mark (get-buffer-process (current-buffer))))
116 (insert (org-babel-chomp body)))
117 buffer)))
119 ;; helper functions
121 (defun org-babel-variable-assignments:python (params)
122 "Return a list of Python statements assigning the block's variables."
123 (mapcar
124 (lambda (pair)
125 (format "%s=%s"
126 (car pair)
127 (org-babel-python-var-to-python (cdr pair))))
128 (org-babel--get-vars params)))
130 (defun org-babel-python-var-to-python (var)
131 "Convert an elisp value to a python variable.
132 Convert an elisp value, VAR, into a string of python source code
133 specifying a variable of the same value."
134 (if (listp var)
135 (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
136 (if (eq var 'hline)
137 org-babel-python-hline-to
138 (format
139 (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
140 (if (stringp var) (substring-no-properties var) var)))))
142 (defun org-babel-python-table-or-string (results)
143 "Convert RESULTS into an appropriate elisp value.
144 If the results look like a list or tuple, then convert them into an
145 Emacs-lisp table, otherwise return the results as a string."
146 (let ((res (org-babel-script-escape results)))
147 (if (listp res)
148 (mapcar (lambda (el) (if (eq el 'None)
149 org-babel-python-None-to el))
150 res)
151 res)))
153 (defvar org-babel-python-buffers '((:default . "*Python*")))
155 (defun org-babel-python-session-buffer (session)
156 "Return the buffer associated with SESSION."
157 (cdr (assoc session org-babel-python-buffers)))
159 (defun org-babel-python-with-earmuffs (session)
160 (let ((name (if (stringp session) session (format "%s" session))))
161 (if (and (string= "*" (substring name 0 1))
162 (string= "*" (substring name (- (length name) 1))))
163 name
164 (format "*%s*" name))))
166 (defun org-babel-python-without-earmuffs (session)
167 (let ((name (if (stringp session) session (format "%s" session))))
168 (if (and (string= "*" (substring name 0 1))
169 (string= "*" (substring name (- (length name) 1))))
170 (substring name 1 (- (length name) 1))
171 name)))
173 (defvar py-default-interpreter)
174 (defvar py-which-bufname)
175 (defvar python-shell-buffer-name)
176 (defun org-babel-python-initiate-session-by-key (&optional session)
177 "Initiate a python session.
178 If there is not a current inferior-process-buffer in SESSION
179 then create. Return the initialized session."
180 (require org-babel-python-mode)
181 (save-window-excursion
182 (let* ((session (if session (intern session) :default))
183 (python-buffer (org-babel-python-session-buffer session))
184 (cmd (if (member system-type '(cygwin windows-nt ms-dos))
185 (concat org-babel-python-command " -i")
186 org-babel-python-command)))
187 (cond
188 ((and (eq 'python org-babel-python-mode)
189 (fboundp 'run-python)) ; python.el
190 (if (not (version< "24.1" emacs-version))
191 (run-python cmd)
192 (unless python-buffer
193 (setq python-buffer (org-babel-python-with-earmuffs session)))
194 (let ((python-shell-buffer-name
195 (org-babel-python-without-earmuffs python-buffer)))
196 (run-python cmd))))
197 ((and (eq 'python-mode org-babel-python-mode)
198 (fboundp 'py-shell)) ; python-mode.el
199 ;; Make sure that py-which-bufname is initialized, as otherwise
200 ;; it will be overwritten the first time a Python buffer is
201 ;; created.
202 (py-toggle-shells py-default-interpreter)
203 ;; `py-shell' creates a buffer whose name is the value of
204 ;; `py-which-bufname' with '*'s at the beginning and end
205 (let* ((bufname (if (and python-buffer (buffer-live-p python-buffer))
206 (replace-regexp-in-string ;; zap surrounding *
207 "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer)
208 (concat "Python-" (symbol-name session))))
209 (py-which-bufname bufname))
210 (py-shell)
211 (setq python-buffer (org-babel-python-with-earmuffs bufname))))
213 (error "No function available for running an inferior Python")))
214 (setq org-babel-python-buffers
215 (cons (cons session python-buffer)
216 (assq-delete-all session org-babel-python-buffers)))
217 session)))
219 (defun org-babel-python-initiate-session (&optional session _params)
220 "Create a session named SESSION according to PARAMS."
221 (unless (string= session "none")
222 (org-babel-python-session-buffer
223 (org-babel-python-initiate-session-by-key session))))
225 (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
226 "A string to indicate that evaluation has completed.")
227 (defconst org-babel-python-wrapper-method
229 def main():
232 open('%s', 'w').write( str(main()) )")
233 (defconst org-babel-python-pp-wrapper-method
235 import pprint
236 def main():
239 open('%s', 'w').write( pprint.pformat(main()) )")
241 (defconst org-babel-python--exec-tmpfile
242 (concat
243 "__org_babel_python_fname = '%s'; "
244 "__org_babel_python_fh = open(__org_babel_python_fname); "
245 "exec(compile("
246 "__org_babel_python_fh.read(), __org_babel_python_fname, 'exec'"
247 ")); "
248 "__org_babel_python_fh.close()"))
250 (defun org-babel-python-evaluate
251 (session body &optional result-type result-params preamble)
252 "Evaluate BODY as Python code."
253 (if session
254 (org-babel-python-evaluate-session
255 session body result-type result-params)
256 (org-babel-python-evaluate-external-process
257 body result-type result-params preamble)))
259 (defun org-babel-python-evaluate-external-process
260 (body &optional result-type result-params preamble)
261 "Evaluate BODY in external python process.
262 If RESULT-TYPE equals `output' then return standard output as a
263 string. If RESULT-TYPE equals `value' then return the value of the
264 last statement in BODY, as elisp."
265 (let ((raw
266 (pcase result-type
267 (`output (org-babel-eval org-babel-python-command
268 (concat preamble (and preamble "\n")
269 body)))
270 (`value (let ((tmp-file (org-babel-temp-file "python-")))
271 (org-babel-eval
272 org-babel-python-command
273 (concat
274 preamble (and preamble "\n")
275 (format
276 (if (member "pp" result-params)
277 org-babel-python-pp-wrapper-method
278 org-babel-python-wrapper-method)
279 (mapconcat
280 (lambda (line) (format "\t%s" line))
281 (split-string (org-remove-indentation (org-trim body))
282 "[\r\n]")
283 "\n")
284 (org-babel-process-file-name tmp-file 'noquote))))
285 (org-babel-eval-read-file tmp-file))))))
286 (org-babel-result-cond result-params
288 (org-babel-python-table-or-string (org-trim raw)))))
290 (defun org-babel-python-evaluate-session
291 (session body &optional result-type result-params)
292 "Pass BODY to the Python process in SESSION.
293 If RESULT-TYPE equals `output' then return standard output as a
294 string. If RESULT-TYPE equals `value' then return the value of the
295 last statement in BODY, as elisp."
296 (let* ((send-wait (lambda () (comint-send-input nil t) (sleep-for 0 5)))
297 (dump-last-value
298 (lambda
299 (tmp-file pp)
300 (mapc
301 (lambda (statement) (insert statement) (funcall send-wait))
302 (if pp
303 (list
304 "import pprint"
305 (format "open('%s', 'w').write(pprint.pformat(_))"
306 (org-babel-process-file-name tmp-file 'noquote)))
307 (list (format "open('%s', 'w').write(str(_))"
308 (org-babel-process-file-name tmp-file
309 'noquote)))))))
310 (last-indent 0)
311 (input-body (lambda (body)
312 (dolist (line (split-string body "[\r\n]"))
313 ;; Insert a blank line to end an indent
314 ;; block.
315 (let ((curr-indent (string-match "\\S-" line)))
316 (if curr-indent
317 (progn
318 (when (< curr-indent last-indent)
319 (insert "")
320 (funcall send-wait))
321 (setq last-indent curr-indent))
322 (setq last-indent 0)))
323 (insert line)
324 (funcall send-wait))
325 (funcall send-wait)))
326 (results
327 (pcase result-type
328 (`output
329 (let ((body (if (string-match-p ".\n+." body) ; Multiline
330 (let ((tmp-src-file (org-babel-temp-file
331 "python-")))
332 (with-temp-file tmp-src-file (insert body))
333 (format org-babel-python--exec-tmpfile
334 tmp-src-file))
335 body)))
336 (mapconcat
337 #'org-trim
338 (butlast
339 (org-babel-comint-with-output
340 (session org-babel-python-eoe-indicator t body)
341 (funcall input-body body)
342 (funcall send-wait) (funcall send-wait)
343 (insert org-babel-python-eoe-indicator)
344 (funcall send-wait))
345 2) "\n")))
346 (`value
347 (let ((tmp-file (org-babel-temp-file "python-")))
348 (org-babel-comint-with-output
349 (session org-babel-python-eoe-indicator nil body)
350 (let ((comint-process-echoes nil))
351 (funcall input-body body)
352 (funcall dump-last-value tmp-file
353 (member "pp" result-params))
354 (funcall send-wait) (funcall send-wait)
355 (insert org-babel-python-eoe-indicator)
356 (funcall send-wait)))
357 (org-babel-eval-read-file tmp-file))))))
358 (unless (string= (substring org-babel-python-eoe-indicator 1 -1) results)
359 (org-babel-result-cond result-params
360 results
361 (org-babel-python-table-or-string results)))))
363 (defun org-babel-python-read-string (string)
364 "Strip \\='s from around Python string."
365 (if (and (string-prefix-p "'" string)
366 (string-suffix-p "'" string))
367 (substring string 1 -1)
368 string))
370 (provide 'ob-python)
374 ;;; ob-python.el ends here