ob-python.el 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 'ob-run)
  25. (require (if (featurep 'xemacs) 'python-mode 'python))
  26. (eval-when-compile (require 'cl))
  27. (declare-function org-remove-indentation "org" )
  28. (add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
  29. (defvar org-babel-default-header-args:python '())
  30. (defvar org-babel-python-command "python"
  31. "Name of command to use for executing python code.")
  32. (defun org-babel-expand-body:python (body params &optional processed-params)
  33. "Expand BODY according to PARAMS, return the expanded body."
  34. (concat
  35. (mapconcat ;; define any variables
  36. (lambda (pair)
  37. (format "%s=%s"
  38. (car pair)
  39. (org-babel-python-var-to-python (cdr pair))))
  40. (nth 1 (or processed-params (org-babel-process-params params))) "\n")
  41. "\n" (org-babel-trim body) "\n"))
  42. (defun org-babel-execute:python (body params)
  43. "Execute a block of Python code with org-babel. This function is
  44. called by `org-babel-execute-src-block'."
  45. (message "executing Python source code block")
  46. (let* ((processed-params (org-babel-process-params params))
  47. (session (org-babel-python-initiate-session (first processed-params)))
  48. (result-params (nth 2 processed-params))
  49. (result-type (nth 3 processed-params))
  50. (full-body (org-babel-expand-body:python
  51. body params processed-params))
  52. (result (org-babel-python-evaluate
  53. session full-body result-type result-params)))
  54. (or (cdr (assoc :file params))
  55. (org-babel-reassemble-table
  56. result
  57. (org-babel-pick-name (nth 4 processed-params)
  58. (cdr (assoc :colnames params)))
  59. (org-babel-pick-name (nth 5 processed-params)
  60. (cdr (assoc :rownames params)))))))
  61. (defun org-babel-prep-session:python (session params)
  62. "Prepare SESSION according to the header arguments specified in PARAMS."
  63. (let* ((session (org-babel-python-initiate-session session))
  64. (vars (org-babel-ref-variables params))
  65. (var-lines (mapcar ;; define any variables
  66. (lambda (pair)
  67. (format "%s=%s"
  68. (car pair)
  69. (org-babel-python-var-to-python (cdr pair))))
  70. vars)))
  71. (org-babel-comint-in-buffer session
  72. (mapc (lambda (var)
  73. (end-of-line 1) (insert var) (comint-send-input)
  74. (org-babel-comint-wait-for-output session)) var-lines))
  75. session))
  76. (defun org-babel-load-session:python (session body params)
  77. "Load BODY into SESSION."
  78. (save-window-excursion
  79. (let ((buffer (org-babel-prep-session:python session params)))
  80. (with-current-buffer buffer
  81. (goto-char (process-mark (get-buffer-process (current-buffer))))
  82. (insert (org-babel-chomp body)))
  83. buffer)))
  84. ;; helper functions
  85. (defun org-babel-python-var-to-python (var)
  86. "Convert an elisp var into a string of python source code
  87. specifying a var of the same value."
  88. (if (listp var)
  89. (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
  90. (if (equal var 'hline) "None" (format "%S" var))))
  91. (defun org-babel-python-table-or-string (results)
  92. "If the results look like a list or tuple, then convert them into an
  93. Emacs-lisp table, otherwise return the results as a string."
  94. ((lambda (res)
  95. (if (listp res)
  96. (mapcar (lambda (el) (if (equal el 'None) 'hline el)) res)
  97. res))
  98. (org-babel-read
  99. (if (or (string-match "^\\[.+\\]$" results)
  100. (string-match "^(.+)$" results))
  101. (org-babel-read
  102. (concat "'"
  103. (replace-regexp-in-string
  104. "\\[" "(" (replace-regexp-in-string
  105. "\\]" ")" (replace-regexp-in-string
  106. ", " " " (replace-regexp-in-string
  107. "'" "\"" results t))))))
  108. results))))
  109. (defvar org-babel-python-buffers '((:default . nil)))
  110. (defun org-babel-python-session-buffer (session)
  111. "Return the buffer associated with SESSION."
  112. (cdr (assoc session org-babel-python-buffers)))
  113. (defun org-babel-python-initiate-session-by-key (&optional session)
  114. "If there is not a current inferior-process-buffer in SESSION
  115. then create. Return the initialized session."
  116. (save-window-excursion
  117. (let* ((session (if session (intern session) :default))
  118. (python-buffer (org-babel-python-session-buffer session)))
  119. (cond
  120. ((fboundp 'run-python) ; python.el
  121. (run-python))
  122. ((fboundp 'py-shell) ; python-mode.el
  123. ;; `py-shell' creates a buffer whose name is the value of
  124. ;; `py-which-bufname' with '*'s at the beginning and end
  125. (let* ((bufname (if python-buffer
  126. (replace-regexp-in-string ;; zap surrounding *
  127. "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer)
  128. (concat "Python-" (symbol-name session))))
  129. (py-which-bufname bufname))
  130. (py-shell)
  131. (setq python-buffer (concat "*" bufname "*"))))
  132. (t
  133. (error "No function available for running an inferior python.")))
  134. (setq org-babel-python-buffers
  135. (cons (cons session python-buffer)
  136. (assq-delete-all session org-babel-python-buffers)))
  137. session)))
  138. (defun org-babel-python-initiate-session (&optional session params)
  139. "Create a session named SESSION according to PARAMS."
  140. (unless (string= session "none")
  141. (org-babel-python-session-buffer
  142. (org-babel-python-initiate-session-by-key session))))
  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. (case result-type
  165. (output (org-babel-eval org-babel-python-command body))
  166. (value (let ((tmp-file (make-temp-file "org-babel-python-results-")))
  167. (org-babel-eval org-babel-python-command
  168. (format
  169. (if (member "pp" result-params)
  170. org-babel-python-pp-wrapper-method
  171. org-babel-python-wrapper-method)
  172. (mapconcat
  173. (lambda (line) (format "\t%s" line))
  174. (split-string
  175. (org-remove-indentation
  176. (org-babel-trim body))
  177. "[\r\n]") "\n")
  178. tmp-file))
  179. ((lambda (raw)
  180. (if (or (member "code" result-params)
  181. (member "pp" result-params))
  182. raw
  183. (org-babel-python-table-or-string raw)))
  184. (org-babel-eval-read-file tmp-file)))))
  185. ;; comint session evaluation
  186. (flet ((dump-last-value (tmp-file pp)
  187. (mapc
  188. (lambda (statement) (insert statement) (comint-send-input))
  189. (if pp
  190. (list
  191. "import pp"
  192. (format "open('%s', 'w').write(pprint.pformat(_))" tmp-file))
  193. (list (format "open('%s', 'w').write(str(_))" tmp-file)))))
  194. (input-body (body)
  195. (mapc (lambda (statement) (insert statement) (comint-send-input))
  196. (split-string (org-babel-trim body) "[\r\n]+"))
  197. (comint-send-input) (comint-send-input)))
  198. (case result-type
  199. (output
  200. (mapconcat
  201. #'org-babel-trim
  202. (butlast
  203. (org-babel-comint-with-output
  204. (buffer org-babel-python-eoe-indicator t body)
  205. (let ((comint-process-echoes nil))
  206. (input-body body)
  207. (insert org-babel-python-eoe-indicator)
  208. (comint-send-input))) 2) "\n"))
  209. (value
  210. ((lambda (results)
  211. (if (or (member "code" result-params) (member "pp" result-params))
  212. results
  213. (org-babel-python-table-or-string results)))
  214. (let ((tmp-file (make-temp-file "org-babel-python-results-")))
  215. (org-babel-comint-with-output
  216. (buffer org-babel-python-eoe-indicator t body)
  217. (let ((comint-process-echoes nil))
  218. (input-body body)
  219. (dump-last-value tmp-file (member "pp" result-params))
  220. (comint-send-input) (comint-send-input)
  221. (insert org-babel-python-eoe-indicator)
  222. (comint-send-input)))
  223. (org-babel-eval-read-file tmp-file))))))))
  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