Make org-publish-attachment honor directory structure
[org-mode.git] / lisp / ob-python.el
blob1d2e8f5773677d50c127a79c444af71c7165fc4a
1 ;;; ob-python.el --- org-babel functions for python evaluation
3 ;; Copyright (C) 2009, 2010 Free Software Foundation
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.01trans
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/>.
25 ;;; Commentary:
27 ;; Org-Babel support for evaluating python source code.
29 ;;; Code:
30 (require 'ob)
31 (require 'ob-ref)
32 (require 'ob-comint)
33 (require 'ob-eval)
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 run-python "ext:python" (&optional cmd noshow new))
40 (add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
42 (defvar org-babel-default-header-args:python '())
44 (defvar org-babel-python-command "python"
45 "Name of command for executing python code.")
47 (defvar org-babel-python-mode (if (featurep 'xemacs) 'python-mode 'python)
48 "Preferred python mode for use in running python interactively.")
50 (defun org-babel-expand-body:python (body params &optional processed-params)
51 "Expand BODY according to PARAMS, return the expanded body."
52 (concat
53 (mapconcat ;; define any variables
54 (lambda (pair)
55 (format "%s=%s"
56 (car pair)
57 (org-babel-python-var-to-python (cdr pair))))
58 (nth 1 (or processed-params (org-babel-process-params params))) "\n")
59 "\n" (org-babel-trim body) "\n"))
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* ((processed-params (org-babel-process-params params))
65 (session (org-babel-python-initiate-session (first processed-params)))
66 (result-params (nth 2 processed-params))
67 (result-type (nth 3 processed-params))
68 (full-body (org-babel-expand-body:python
69 body params processed-params))
70 (result (org-babel-python-evaluate
71 session full-body result-type result-params)))
72 (or (cdr (assoc :file params))
73 (org-babel-reassemble-table
74 result
75 (org-babel-pick-name (nth 4 processed-params)
76 (cdr (assoc :colnames params)))
77 (org-babel-pick-name (nth 5 processed-params)
78 (cdr (assoc :rownames params)))))))
80 (defun org-babel-prep-session:python (session params)
81 "Prepare SESSION according to the header arguments in PARAMS."
82 (let* ((session (org-babel-python-initiate-session session))
83 (vars (org-babel-ref-variables params))
84 (var-lines (mapcar ;; define any variables
85 (lambda (pair)
86 (format "%s=%s"
87 (car pair)
88 (org-babel-python-var-to-python (cdr pair))))
89 vars)))
90 (org-babel-comint-in-buffer session
91 (mapc (lambda (var)
92 (end-of-line 1) (insert var) (comint-send-input)
93 (org-babel-comint-wait-for-output session)) var-lines))
94 session))
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)))
103 buffer)))
105 ;; helper functions
107 (defun org-babel-python-var-to-python (var)
108 "Convert an elisp value to a python variable.
109 Convert an elisp value, VAR, into a string of python source code
110 specifying a variable of the same value."
111 (if (listp var)
112 (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
113 (if (equal var 'hline)
114 "None"
115 (format
116 (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
117 var))))
119 (defun org-babel-python-table-or-string (results)
120 "Convert RESULTS into an appropriate elisp value.
121 If the results look like a list or tuple, then convert them into an
122 Emacs-lisp table, otherwise return the results as a string."
123 ((lambda (res)
124 (if (listp res)
125 (mapcar (lambda (el) (if (equal el 'None) 'hline el)) res)
126 res))
127 (org-babel-read
128 (if (and (stringp results) (string-match "^[([].+[])]$" results))
129 (org-babel-read
130 (concat "'"
131 (replace-regexp-in-string
132 "\\[" "(" (replace-regexp-in-string
133 "\\]" ")" (replace-regexp-in-string
134 ", " " " (replace-regexp-in-string
135 "'" "\"" results t))))))
136 results))))
138 (defvar org-babel-python-buffers '((:default . nil)))
140 (defun org-babel-python-session-buffer (session)
141 "Return the buffer associated with SESSION."
142 (cdr (assoc session org-babel-python-buffers)))
144 (defun org-babel-python-initiate-session-by-key (&optional session)
145 "Initiate a python session.
146 If there is not a current inferior-process-buffer in SESSION
147 then create. Return the initialized session."
148 (require org-babel-python-mode)
149 (save-window-excursion
150 (let* ((session (if session (intern session) :default))
151 (python-buffer (org-babel-python-session-buffer session)))
152 (cond
153 ((and (eq 'python org-babel-python-mode)
154 (fboundp 'run-python)) ; python.el
155 (run-python))
156 ((and (eq 'python-mode org-babel-python-mode)
157 (fboundp 'py-shell)) ; python-mode.el
158 ;; `py-shell' creates a buffer whose name is the value of
159 ;; `py-which-bufname' with '*'s at the beginning and end
160 (let* ((bufname (if python-buffer
161 (replace-regexp-in-string ;; zap surrounding *
162 "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer)
163 (concat "Python-" (symbol-name session))))
164 (py-which-bufname bufname))
165 (py-shell)
166 (setq python-buffer (concat "*" bufname "*"))))
168 (error "No function available for running an inferior python.")))
169 (setq org-babel-python-buffers
170 (cons (cons session python-buffer)
171 (assq-delete-all session org-babel-python-buffers)))
172 session)))
174 (defun org-babel-python-initiate-session (&optional session params)
175 "Create a session named SESSION according to PARAMS."
176 (unless (string= session "none")
177 (org-babel-python-session-buffer
178 (org-babel-python-initiate-session-by-key session))))
180 (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
181 "A string to indicate that evaluation has completed.")
182 (defvar org-babel-python-wrapper-method
184 def main():
187 open('%s', 'w').write( str(main()) )")
188 (defvar org-babel-python-pp-wrapper-method
190 import pprint
191 def main():
194 open('%s', 'w').write( pprint.pformat(main()) )")
196 (defun org-babel-python-evaluate
197 (session body &optional result-type result-params)
198 "Evaluate BODY as python code."
199 (if session
200 (org-babel-python-evaluate-session
201 session body result-type result-params)
202 (org-babel-python-evaluate-external-process
203 body result-type result-params)))
205 (defun org-babel-python-evaluate-external-process
206 (body &optional result-type result-params)
207 "Evaluate BODY in external python process.
208 If RESULT-TYPE equals 'output then return standard output as a
209 string. If RESULT-TYPE equals 'value then return the value of the
210 last statement in BODY, as elisp."
211 (case result-type
212 (output (org-babel-eval org-babel-python-command body))
213 (value (let ((tmp-file (org-babel-temp-file "python-results-")))
214 (org-babel-eval org-babel-python-command
215 (format
216 (if (member "pp" result-params)
217 org-babel-python-pp-wrapper-method
218 org-babel-python-wrapper-method)
219 (mapconcat
220 (lambda (line) (format "\t%s" line))
221 (split-string
222 (org-remove-indentation
223 (org-babel-trim body))
224 "[\r\n]") "\n")
225 tmp-file))
226 ((lambda (raw)
227 (if (or (member "code" result-params)
228 (member "pp" result-params))
230 (org-babel-python-table-or-string raw)))
231 (org-babel-eval-read-file tmp-file))))))
233 (defun org-babel-python-evaluate-session
234 (session body &optional result-type result-params)
235 "Pass BODY to the Python process in SESSION.
236 If RESULT-TYPE equals 'output then return standard output as a
237 string. If RESULT-TYPE equals 'value then return the value of the
238 last statement in BODY, as elisp."
239 (flet ((dump-last-value
240 (tmp-file pp)
241 (mapc
242 (lambda (statement) (insert statement) (comint-send-input))
243 (if pp
244 (list
245 "import pp"
246 (format "open('%s', 'w').write(pprint.pformat(_))" tmp-file))
247 (list (format "open('%s', 'w').write(str(_))" tmp-file)))))
248 (input-body (body)
249 (mapc (lambda (statement) (insert statement) (comint-send-input))
250 (split-string (org-babel-trim body) "[\r\n]+"))
251 (comint-send-input) (comint-send-input)))
252 (case result-type
253 (output
254 (mapconcat
255 #'org-babel-trim
256 (butlast
257 (org-babel-comint-with-output
258 (session org-babel-python-eoe-indicator t body)
259 (let ((comint-process-echoes nil))
260 (input-body body)
261 (insert org-babel-python-eoe-indicator)
262 (comint-send-input))) 2) "\n"))
263 (value
264 ((lambda (results)
265 (if (or (member "code" result-params) (member "pp" result-params))
266 results
267 (org-babel-python-table-or-string results)))
268 (let ((tmp-file (org-babel-temp-file "python-results-")))
269 (org-babel-comint-with-output
270 (session org-babel-python-eoe-indicator t body)
271 (let ((comint-process-echoes nil))
272 (input-body body)
273 (dump-last-value tmp-file (member "pp" result-params))
274 (comint-send-input) (comint-send-input)
275 (insert org-babel-python-eoe-indicator)
276 (comint-send-input)))
277 (org-babel-eval-read-file tmp-file)))))))
279 (defun org-babel-python-read-string (string)
280 "Strip 's from around python string"
281 (if (string-match "^'\\([^\000]+\\)'$" string)
282 (match-string 1 string)
283 string))
285 (provide 'ob-python)
287 ;; arch-tag: f19b6c3d-dfcb-4a1a-9ce0-45ade1ebc212
289 ;;; ob-python.el ends here