ob-python.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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: 7.01trans
  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 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 Babel.
  47. This function is 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 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 value to a python variable.
  89. Convert an elisp value, VAR, into a string of python source code
  90. specifying a variable of the same value."
  91. (if (listp var)
  92. (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
  93. (if (equal var 'hline)
  94. "None"
  95. (format
  96. (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
  97. var))))
  98. (defun org-babel-python-table-or-string (results)
  99. "Convert RESULTS into an appropriate elisp value.
  100. If the results look like a list or tuple, then convert them into an
  101. Emacs-lisp table, otherwise return the results as a string."
  102. ((lambda (res)
  103. (if (listp res)
  104. (mapcar (lambda (el) (if (equal el 'None) 'hline el)) res)
  105. res))
  106. (org-babel-read
  107. (if (and (stringp results) (string-match "^[([].+[])]$" results))
  108. (org-babel-read
  109. (concat "'"
  110. (replace-regexp-in-string
  111. "\\[" "(" (replace-regexp-in-string
  112. "\\]" ")" (replace-regexp-in-string
  113. ", " " " (replace-regexp-in-string
  114. "'" "\"" results t))))))
  115. results))))
  116. (defvar org-babel-python-buffers '((:default . nil)))
  117. (defun org-babel-python-session-buffer (session)
  118. "Return the buffer associated with SESSION."
  119. (cdr (assoc session org-babel-python-buffers)))
  120. (defun org-babel-python-initiate-session-by-key (&optional session)
  121. "Initiate a python session.
  122. If there is not a current inferior-process-buffer in SESSION
  123. then create. Return the initialized session."
  124. (require org-babel-python-mode)
  125. (save-window-excursion
  126. (let* ((session (if session (intern session) :default))
  127. (python-buffer (org-babel-python-session-buffer session)))
  128. (cond
  129. ((and (eq 'python org-babel-python-mode)
  130. (fboundp 'run-python)) ; python.el
  131. (run-python))
  132. ((and (eq 'python-mode org-babel-python-mode)
  133. (fboundp 'py-shell)) ; python-mode.el
  134. ;; `py-shell' creates a buffer whose name is the value of
  135. ;; `py-which-bufname' with '*'s at the beginning and end
  136. (let* ((bufname (if python-buffer
  137. (replace-regexp-in-string ;; zap surrounding *
  138. "^\\*\\([^*]+\\)\\*$" "\\1" python-buffer)
  139. (concat "Python-" (symbol-name session))))
  140. (py-which-bufname bufname))
  141. (py-shell)
  142. (setq python-buffer (concat "*" bufname "*"))))
  143. (t
  144. (error "No function available for running an inferior python.")))
  145. (setq org-babel-python-buffers
  146. (cons (cons session python-buffer)
  147. (assq-delete-all session org-babel-python-buffers)))
  148. session)))
  149. (defun org-babel-python-initiate-session (&optional session params)
  150. "Create a session named SESSION according to PARAMS."
  151. (unless (string= session "none")
  152. (org-babel-python-session-buffer
  153. (org-babel-python-initiate-session-by-key session))))
  154. (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
  155. "A string to indicate that evaluation has completed.")
  156. (defvar org-babel-python-wrapper-method
  157. "
  158. def main():
  159. %s
  160. open('%s', 'w').write( str(main()) )")
  161. (defvar org-babel-python-pp-wrapper-method
  162. "
  163. import pprint
  164. def main():
  165. %s
  166. open('%s', 'w').write( pprint.pformat(main()) )")
  167. (defun org-babel-python-evaluate
  168. (session body &optional result-type result-params)
  169. "Evaluate BODY as python code."
  170. (if session
  171. (org-babel-python-evaluate-session
  172. session body result-type result-params)
  173. (org-babel-python-evaluate-external-process
  174. body result-type result-params)))
  175. (defun org-babel-python-evaluate-external-process
  176. (body &optional result-type result-params)
  177. "Evaluate BODY in external python process.
  178. If RESULT-TYPE equals 'output then return standard output as a
  179. string. If RESULT-TYPE equals 'value then return the value of the
  180. last statement in BODY, as elisp."
  181. (case result-type
  182. (output (org-babel-eval org-babel-python-command body))
  183. (value (let ((tmp-file (org-babel-temp-file "python-")))
  184. (org-babel-eval org-babel-python-command
  185. (format
  186. (if (member "pp" result-params)
  187. org-babel-python-pp-wrapper-method
  188. org-babel-python-wrapper-method)
  189. (mapconcat
  190. (lambda (line) (format "\t%s" line))
  191. (split-string
  192. (org-remove-indentation
  193. (org-babel-trim body))
  194. "[\r\n]") "\n")
  195. (org-babel-process-file-name tmp-file 'noquote)))
  196. ((lambda (raw)
  197. (if (or (member "code" result-params)
  198. (member "pp" result-params))
  199. raw
  200. (org-babel-python-table-or-string raw)))
  201. (org-babel-eval-read-file tmp-file))))))
  202. (defun org-babel-python-evaluate-session
  203. (session body &optional result-type result-params)
  204. "Pass BODY to the Python process in SESSION.
  205. If RESULT-TYPE equals 'output then return standard output as a
  206. string. If RESULT-TYPE equals 'value then return the value of the
  207. last statement in BODY, as elisp."
  208. (flet ((dump-last-value
  209. (tmp-file pp)
  210. (mapc
  211. (lambda (statement) (insert statement) (comint-send-input))
  212. (if pp
  213. (list
  214. "import pp"
  215. (format "open('%s', 'w').write(pprint.pformat(_))"
  216. (org-babel-process-file-name tmp-file 'noquote)))
  217. (list (format "open('%s', 'w').write(str(_))"
  218. (org-babel-process-file-name tmp-file 'noquote))))))
  219. (input-body (body)
  220. (mapc (lambda (statement) (insert statement) (comint-send-input))
  221. (split-string (org-babel-trim body) "[\r\n]+"))
  222. (comint-send-input) (comint-send-input)))
  223. (case result-type
  224. (output
  225. (mapconcat
  226. #'org-babel-trim
  227. (butlast
  228. (org-babel-comint-with-output
  229. (session org-babel-python-eoe-indicator t body)
  230. (let ((comint-process-echoes nil))
  231. (input-body body)
  232. (insert org-babel-python-eoe-indicator)
  233. (comint-send-input))) 2) "\n"))
  234. (value
  235. ((lambda (results)
  236. (if (or (member "code" result-params) (member "pp" result-params))
  237. results
  238. (org-babel-python-table-or-string results)))
  239. (let ((tmp-file (org-babel-temp-file "python-results-")))
  240. (org-babel-comint-with-output
  241. (session org-babel-python-eoe-indicator t body)
  242. (let ((comint-process-echoes nil))
  243. (input-body body)
  244. (dump-last-value tmp-file (member "pp" result-params))
  245. (comint-send-input) (comint-send-input)
  246. (insert org-babel-python-eoe-indicator)
  247. (comint-send-input)))
  248. (org-babel-eval-read-file tmp-file)))))))
  249. (defun org-babel-python-read-string (string)
  250. "Strip 's from around python string"
  251. (if (string-match "^'\\([^\000]+\\)'$" string)
  252. (match-string 1 string)
  253. string))
  254. (provide 'ob-python)
  255. ;; arch-tag: f19b6c3d-dfcb-4a1a-9ce0-45ade1ebc212
  256. ;;; ob-python.el ends here