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