ob-python.el 10 KB

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