ob-python.el 10 KB

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