ob-python.el 10 KB

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