ob-python.el 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. ;;; ob-python.el --- org-babel functions for python evaluation
  2. ;; Copyright (C) 2009, 2010 Free Software Foundation
  3. ;; Author: Eric Schulte, Dan Davison
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;; This file is part of GNU Emacs.
  8. ;; GNU Emacs is free software: you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation, either version 3 of the License, or
  11. ;; (at your option) any later version.
  12. ;; GNU Emacs is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  18. ;;; Commentary:
  19. ;; Org-Babel support for evaluating python source code.
  20. ;;; Code:
  21. (require 'ob)
  22. (require 'ob-ref)
  23. (require 'ob-comint)
  24. (require (if (featurep 'xemacs) 'python-mode 'python))
  25. (eval-when-compile (require 'cl))
  26. (declare-function org-remove-indentation "org" )
  27. (add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
  28. (defvar org-babel-default-header-args:python '())
  29. (defun org-babel-expand-body:python (body params &optional processed-params)
  30. "Expand BODY according to PARAMS, return the expanded body."
  31. (concat
  32. (mapconcat ;; define any variables
  33. (lambda (pair)
  34. (format "%s=%s"
  35. (car pair)
  36. (org-babel-python-var-to-python (cdr pair))))
  37. (nth 1 (or processed-params (org-babel-process-params params))) "\n")
  38. "\n" (org-babel-trim body) "\n"))
  39. (defun org-babel-execute:python (body params)
  40. "Execute a block of Python code with org-babel. This function is
  41. called by `org-babel-execute-src-block'."
  42. (message "executing Python source code block")
  43. (let* ((processed-params (org-babel-process-params params))
  44. (session (org-babel-python-initiate-session (first processed-params)))
  45. (result-params (nth 2 processed-params))
  46. (result-type (nth 3 processed-params))
  47. (full-body (org-babel-expand-body:python
  48. body params processed-params)) ;; then the source block body
  49. (result (org-babel-python-evaluate
  50. session full-body result-type result-params)))
  51. (or (cdr (assoc :file params))
  52. (org-babel-reassemble-table
  53. result
  54. (org-babel-pick-name (nth 4 processed-params) (cdr (assoc :colnames params)))
  55. (org-babel-pick-name (nth 5 processed-params) (cdr (assoc :rownames params)))))))
  56. (defun org-babel-prep-session:python (session params)
  57. "Prepare SESSION according to the header arguments specified in PARAMS."
  58. (let* ((session (org-babel-python-initiate-session session))
  59. (vars (org-babel-ref-variables params))
  60. (var-lines (mapcar ;; define any variables
  61. (lambda (pair)
  62. (format "%s=%s"
  63. (car pair)
  64. (org-babel-python-var-to-python (cdr pair))))
  65. vars)))
  66. (org-babel-comint-in-buffer session
  67. (mapc (lambda (var)
  68. (end-of-line 1) (insert var) (comint-send-input)
  69. (org-babel-comint-wait-for-output session)) var-lines))
  70. session))
  71. (defun org-babel-load-session:python (session body params)
  72. "Load BODY into SESSION."
  73. (save-window-excursion
  74. (let ((buffer (org-babel-prep-session:python session params)))
  75. (with-current-buffer buffer
  76. (goto-char (process-mark (get-buffer-process (current-buffer))))
  77. (insert (org-babel-chomp body)))
  78. buffer)))
  79. ;; helper functions
  80. (defun org-babel-python-var-to-python (var)
  81. "Convert an elisp var into a string of python source code
  82. specifying a var of the same value."
  83. (if (listp var)
  84. (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
  85. (if (equal var 'hline) "None" (format "%S" var))))
  86. (defun org-babel-python-table-or-string (results)
  87. "If the results look like a list or tuple, then convert them into an
  88. Emacs-lisp table, otherwise return the results as a string."
  89. ((lambda (res)
  90. (if (listp res)
  91. (mapcar (lambda (el) (if (equal el 'None) 'hline el)) res)
  92. res))
  93. (org-babel-read
  94. (if (or (string-match "^\\[.+\\]$" results)
  95. (string-match "^(.+)$" results))
  96. (org-babel-read
  97. (concat "'"
  98. (replace-regexp-in-string
  99. "\\[" "(" (replace-regexp-in-string
  100. "\\]" ")" (replace-regexp-in-string
  101. ", " " " (replace-regexp-in-string
  102. "'" "\"" results t))))))
  103. results))))
  104. (defvar org-babel-python-buffers '((:default . nil)))
  105. (defun org-babel-python-session-buffer (session)
  106. "Return the buffer associated with SESSION."
  107. (cdr (assoc session org-babel-python-buffers)))
  108. (defun org-babel-python-initiate-session-by-key (&optional session)
  109. "If there is not a current inferior-process-buffer in SESSION
  110. then create. Return the initialized session."
  111. (save-window-excursion
  112. (let* ((session (if session (intern session) :default))
  113. (python-buffer (org-babel-python-session-buffer session)))
  114. (cond
  115. ((fboundp 'run-python) ; python.el
  116. (run-python))
  117. ((fboundp 'py-shell) ; python-mode.el
  118. ;; `py-shell' creates a buffer whose name is the value of
  119. ;; `py-which-bufname' with '*'s at the beginning and end
  120. (let* ((bufname (if python-buffer
  121. (replace-regexp-in-string "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer) ; zap surrounding *
  122. (concat "Python-" (symbol-name session))))
  123. (py-which-bufname bufname)) ; avoid making a mess with buffer-local
  124. (py-shell)
  125. (setq python-buffer (concat "*" bufname "*"))))
  126. (t
  127. (error "No function available for running an inferior python.")))
  128. (setq org-babel-python-buffers (cons (cons session python-buffer)
  129. (assq-delete-all session org-babel-python-buffers)))
  130. session)))
  131. (defun org-babel-python-initiate-session (&optional session params)
  132. "Create a session named SESSION according to PARAMS."
  133. (unless (string= session "none")
  134. (org-babel-python-session-buffer (org-babel-python-initiate-session-by-key session))))
  135. (defvar org-babel-python-last-value-eval "_"
  136. "When evaluated by Python this returns the return value of the last statement.")
  137. (defvar org-babel-python-pp-last-value-eval
  138. '("results = _"
  139. "import pprint"
  140. "org_babel_pp = pprint.PrettyPrinter()"
  141. "org_babel_pp.pprint(results)")
  142. "When evaluated by Python this pretty prints the value of the last statement.")
  143. (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
  144. "Used to indicate that evaluation is has completed.")
  145. (defvar org-babel-python-wrapper-method
  146. "
  147. def main():
  148. %s
  149. open('%s', 'w').write( str(main()) )")
  150. (defvar org-babel-python-pp-wrapper-method
  151. "
  152. import pprint
  153. def main():
  154. %s
  155. open('%s', 'w').write( pprint.pformat(main()) )")
  156. (defun org-babel-python-evaluate
  157. (buffer body &optional result-type result-params)
  158. "Pass BODY to the Python process in BUFFER. If RESULT-TYPE equals
  159. 'output then return a list of the outputs of the statements in
  160. BODY, if RESULT-TYPE equals 'value then return the value of the
  161. last statement in BODY, as elisp."
  162. (if (not buffer)
  163. ;; external process evaluation
  164. (save-excursion
  165. (case result-type
  166. (output
  167. (with-temp-buffer
  168. (insert body)
  169. ;; (message "buffer=%s" (buffer-string)) ;; debugging
  170. (org-babel-shell-command-on-region (point-min) (point-max) "python" 'current-buffer 'replace)
  171. (buffer-string)))
  172. (value
  173. (let* ((tmp-file (make-temp-file "org-babel-python-results-")) exit-code
  174. (stderr
  175. (with-temp-buffer
  176. (insert
  177. (format
  178. (if (member "pp" result-params)
  179. org-babel-python-pp-wrapper-method
  180. org-babel-python-wrapper-method)
  181. (mapconcat
  182. (lambda (line) (format "\t%s" line))
  183. (split-string
  184. (org-remove-indentation (org-babel-trim body)) "[\r\n]") "\n")
  185. tmp-file))
  186. ;; (message "buffer=%s" (buffer-string)) ;; debugging
  187. (setq exit-code (org-babel-shell-command-on-region
  188. (point-min) (point-max) "python" nil 'replace (current-buffer)))
  189. (buffer-string))))
  190. (if (> exit-code 0) (org-babel-error-notify exit-code stderr))
  191. (let ((raw (with-temp-buffer
  192. (insert-file-contents (org-babel-maybe-remote-file tmp-file))
  193. (buffer-string))))
  194. (if (or (member "code" result-params) (member "pp" result-params))
  195. raw
  196. (org-babel-python-table-or-string raw)))))))
  197. ;; comint session evaluation
  198. (org-babel-comint-in-buffer buffer
  199. (let* ((raw (org-babel-comint-with-output
  200. (buffer org-babel-python-eoe-indicator t body)
  201. ;; for some reason python is fussy, and likes enters after every input
  202. (let ((comint-process-echoes nil))
  203. (mapc (lambda (statement) (insert statement) (comint-send-input))
  204. (split-string (org-babel-trim body) "[\r\n]+"))
  205. (comint-send-input) (comint-send-input)
  206. (if (member "pp" result-params)
  207. (mapc (lambda (statement) (insert statement) (comint-send-input))
  208. org-babel-python-pp-last-value-eval)
  209. (insert org-babel-python-last-value-eval))
  210. (comint-send-input) (comint-send-input)
  211. (insert org-babel-python-eoe-indicator)
  212. (comint-send-input))))
  213. (raw (apply #'append ; split further
  214. (mapcar #'(lambda (r)
  215. (split-string r "[\r\n]+"))
  216. raw)))
  217. (results (delete org-babel-python-eoe-indicator
  218. (cdr (member org-babel-python-eoe-indicator
  219. (mapcar #'org-babel-trim raw))))))
  220. (unless (or (member "code" result-params) (member "pp" result-params))
  221. (setq results (mapcar #'org-babel-python-read-string results)))
  222. (case result-type
  223. (output (org-babel-trim (mapconcat #'identity (reverse (cdr results)) "\n")))
  224. (value
  225. (if (or (member "code" result-params) (member "pp" result-params))
  226. (car results)
  227. (org-babel-python-table-or-string (org-babel-trim (car results))))))))))
  228. (defun org-babel-python-read-string (string)
  229. "Strip 's from around python string"
  230. (if (string-match "^'\\([^\000]+\\)'$" string)
  231. (match-string 1 string)
  232. string))
  233. (provide 'ob-python)
  234. ;; arch-tag: f19b6c3d-dfcb-4a1a-9ce0-45ade1ebc212
  235. ;;; ob-python.el ends here