ob-python.el 9.7 KB

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