ob-python.el 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. (org-babel-read
  87. (if (or (string-match "^\\[.+\\]$" results)
  88. (string-match "^(.+)$" results))
  89. (org-babel-read
  90. (concat "'"
  91. (replace-regexp-in-string
  92. "\\[" "(" (replace-regexp-in-string
  93. "\\]" ")" (replace-regexp-in-string
  94. ", " " " (replace-regexp-in-string
  95. "'" "\""
  96. (replace-regexp-in-string
  97. "None" "hline" results t)))))))
  98. results)))
  99. (defvar org-babel-python-buffers '(:default . nil))
  100. (defun org-babel-python-session-buffer (session)
  101. "Return the buffer associated with SESSION."
  102. (cdr (assoc session org-babel-python-buffers)))
  103. (defun org-babel-python-initiate-session-by-key (&optional session)
  104. "If there is not a current inferior-process-buffer in SESSION
  105. then create. Return the initialized session."
  106. (save-window-excursion
  107. (let* ((session (if session (intern session) :default))
  108. (python-buffer (org-babel-python-session-buffer session)))
  109. (cond
  110. ((fboundp 'run-python) ; python.el
  111. (run-python))
  112. ((fboundp 'py-shell) ; python-mode.el
  113. ;; `py-shell' creates a buffer whose name is the value of
  114. ;; `py-which-bufname' with '*'s at the beginning and end
  115. (let* ((bufname (if python-buffer
  116. (replace-regexp-in-string "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer) ; zap surrounding *
  117. (concat "Python-" (symbol-name session))))
  118. (py-which-bufname bufname)) ; avoid making a mess with buffer-local
  119. (py-shell)
  120. (setq python-buffer (concat "*" bufname "*"))))
  121. (t
  122. (error "No function available for running an inferior python.")))
  123. (setq org-babel-python-buffers (cons (cons session python-buffer)
  124. (assq-delete-all session org-babel-python-buffers)))
  125. session)))
  126. (defun org-babel-python-initiate-session (&optional session params)
  127. "Create a session named SESSION according to PARAMS."
  128. (unless (string= session "none")
  129. (org-babel-python-session-buffer (org-babel-python-initiate-session-by-key session))))
  130. (defvar org-babel-python-last-value-eval "_"
  131. "When evaluated by Python this returns the return value of the last statement.")
  132. (defvar org-babel-python-pp-last-value-eval
  133. '("results = _"
  134. "import pprint"
  135. "org_babel_pp = pprint.PrettyPrinter()"
  136. "org_babel_pp.pprint(results)")
  137. "When evaluated by Python this pretty prints the value of the last statement.")
  138. (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
  139. "Used to indicate that evaluation is has completed.")
  140. (defvar org-babel-python-wrapper-method
  141. "
  142. def main():
  143. %s
  144. open('%s', 'w').write( str(main()) )")
  145. (defvar org-babel-python-pp-wrapper-method
  146. "
  147. import pprint
  148. def main():
  149. %s
  150. open('%s', 'w').write( pprint.pformat(main()) )")
  151. (defun org-babel-python-evaluate (buffer body &optional result-type)
  152. "Pass BODY to the Python process in BUFFER. If RESULT-TYPE equals
  153. 'output then return a list of the outputs of the statements in
  154. BODY, if RESULT-TYPE equals 'value then return the value of the
  155. last statement in BODY, as elisp."
  156. (if (not session)
  157. ;; external process evaluation
  158. (save-excursion
  159. (case result-type
  160. (output
  161. (with-temp-buffer
  162. (insert body)
  163. ;; (message "buffer=%s" (buffer-string)) ;; debugging
  164. (org-babel-shell-command-on-region (point-min) (point-max) "python" 'current-buffer 'replace)
  165. (buffer-string)))
  166. (value
  167. (let* ((tmp-file (make-temp-file "org-babel-python-results-")) exit-code
  168. (stderr
  169. (with-temp-buffer
  170. (insert
  171. (format
  172. (if (member "pp" result-params)
  173. org-babel-python-pp-wrapper-method
  174. org-babel-python-wrapper-method)
  175. (mapconcat
  176. (lambda (line) (format "\t%s" line))
  177. (split-string
  178. (org-remove-indentation (org-babel-trim body)) "[\r\n]") "\n")
  179. tmp-file))
  180. ;; (message "buffer=%s" (buffer-string)) ;; debugging
  181. (setq exit-code (org-babel-shell-command-on-region
  182. (point-min) (point-max) "python" nil 'replace (current-buffer)))
  183. (buffer-string))))
  184. (if (> exit-code 0) (org-babel-error-notify exit-code stderr))
  185. (let ((raw (with-temp-buffer
  186. (insert-file-contents (org-babel-maybe-remote-file tmp-file))
  187. (buffer-string))))
  188. (if (or (member "code" result-params) (member "pp" result-params))
  189. raw
  190. (org-babel-python-table-or-string raw)))))))
  191. ;; comint session evaluation
  192. (org-babel-comint-in-buffer buffer
  193. (let* ((raw (org-babel-comint-with-output
  194. (buffer org-babel-python-eoe-indicator t full-body)
  195. ;; for some reason python is fussy, and likes enters after every input
  196. (let ((comint-process-echoes nil))
  197. (mapc (lambda (statement) (insert statement) (comint-send-input))
  198. (split-string (org-babel-trim body) "[\r\n]+"))
  199. (comint-send-input) (comint-send-input)
  200. (if (member "pp" result-params)
  201. (mapc (lambda (statement) (insert statement) (comint-send-input))
  202. org-babel-python-pp-last-value-eval)
  203. (insert org-babel-python-last-value-eval))
  204. (comint-send-input) (comint-send-input)
  205. (insert org-babel-python-eoe-indicator)
  206. (comint-send-input))))
  207. (raw (apply #'append ; split further
  208. (mapcar #'(lambda (r)
  209. (split-string r "[\r\n]+"))
  210. raw)))
  211. (results (delete org-babel-python-eoe-indicator
  212. (cdr (member org-babel-python-eoe-indicator
  213. (mapcar #'org-babel-trim raw))))))
  214. (unless (or (member "code" result-params) (member "pp" result-params))
  215. (setq results (mapcar #'org-babel-python-read-string results)))
  216. (case result-type
  217. (output (org-babel-trim (mapconcat #'identity (reverse (cdr results)) "\n")))
  218. (value
  219. (if (or (member "code" result-params) (member "pp" result-params))
  220. (car results)
  221. (org-babel-python-table-or-string (org-babel-trim (car results))))))))))
  222. (defun org-babel-python-read-string (string)
  223. "Strip 's from around python string"
  224. (if (string-match "^'\\([^\000]+\\)'$" string)
  225. (match-string 1 string)
  226. string))
  227. (provide 'ob-python)
  228. ;; arch-tag: f19b6c3d-dfcb-4a1a-9ce0-45ade1ebc212
  229. ;;; ob-python.el ends here