ob-python.el 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. ;;; ob-python.el --- org-babel functions for python evaluation
  2. ;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Dan Davison
  5. ;; Keywords: literate programming, reproducible research
  6. ;; Homepage: http://orgmode.org
  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. (defvar org-babel-tangle-lang-exts)
  31. (add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
  32. (defvar org-babel-default-header-args:python '())
  33. (defvar org-babel-python-command "python"
  34. "Name of command for executing python code.")
  35. (defvar org-babel-python-mode (if (featurep 'xemacs) 'python-mode 'python)
  36. "Preferred python mode for use in running python interactively.
  37. This will typically be either 'python or 'python-mode.")
  38. (defvar org-src-preserve-indentation)
  39. (defun org-babel-execute:python (body params)
  40. "Execute a block of Python code with Babel.
  41. This function is called by `org-babel-execute-src-block'."
  42. (let* ((session (org-babel-python-initiate-session
  43. (cdr (assoc :session params))))
  44. (result-params (cdr (assoc :result-params params)))
  45. (result-type (cdr (assoc :result-type params)))
  46. (return-val (when (and (eq result-type 'value) (not session))
  47. (cdr (assoc :return params))))
  48. (preamble (cdr (assoc :preamble params)))
  49. (full-body
  50. (org-babel-expand-body:generic
  51. (concat body (if return-val (format "return %s" return-val) ""))
  52. params (org-babel-variable-assignments:python params)))
  53. (result (org-babel-python-evaluate
  54. session full-body result-type result-params preamble)))
  55. (org-babel-reassemble-table
  56. result
  57. (org-babel-pick-name (cdr (assoc :colname-names params))
  58. (cdr (assoc :colnames params)))
  59. (org-babel-pick-name (cdr (assoc :rowname-names params))
  60. (cdr (assoc :rownames params))))))
  61. (defun org-babel-prep-session:python (session params)
  62. "Prepare SESSION according to the header arguments in PARAMS.
  63. VARS contains resolved variable references"
  64. (let* ((session (org-babel-python-initiate-session session))
  65. (var-lines
  66. (org-babel-variable-assignments:python params)))
  67. (org-babel-comint-in-buffer session
  68. (mapc (lambda (var)
  69. (end-of-line 1) (insert var) (comint-send-input)
  70. (org-babel-comint-wait-for-output session)) var-lines))
  71. session))
  72. (defun org-babel-load-session:python (session body params)
  73. "Load BODY into SESSION."
  74. (save-window-excursion
  75. (let ((buffer (org-babel-prep-session:python session params)))
  76. (with-current-buffer buffer
  77. (goto-char (process-mark (get-buffer-process (current-buffer))))
  78. (insert (org-babel-chomp body)))
  79. buffer)))
  80. ;; helper functions
  81. (defun org-babel-variable-assignments:python (params)
  82. "Return list of python statements assigning the block's variables"
  83. (mapcar
  84. (lambda (pair)
  85. (format "%s=%s"
  86. (car pair)
  87. (org-babel-python-var-to-python (cdr pair))))
  88. (mapcar #'cdr (org-babel-get-header params :var))))
  89. (defun org-babel-python-var-to-python (var)
  90. "Convert an elisp value to a python variable.
  91. Convert an elisp value, VAR, into a string of python source code
  92. specifying a variable of the same value."
  93. (if (listp var)
  94. (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
  95. (if (equal var 'hline)
  96. "None"
  97. (format
  98. (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
  99. var))))
  100. (defun org-babel-python-table-or-string (results)
  101. "Convert RESULTS into an appropriate elisp value.
  102. If the results look like a list or tuple, then convert them into an
  103. Emacs-lisp table, otherwise return the results as a string."
  104. (org-babel-script-escape results))
  105. (defvar org-babel-python-buffers '((:default . nil)))
  106. (defun org-babel-python-session-buffer (session)
  107. "Return the buffer associated with SESSION."
  108. (cdr (assoc session org-babel-python-buffers)))
  109. (defvar py-default-interpreter)
  110. (defun org-babel-python-initiate-session-by-key (&optional session)
  111. "Initiate a python session.
  112. If there is not a current inferior-process-buffer in SESSION
  113. then create. Return the initialized session."
  114. (require org-babel-python-mode)
  115. (save-window-excursion
  116. (let* ((session (if session (intern session) :default))
  117. (python-buffer (org-babel-python-session-buffer session)))
  118. (cond
  119. ((and (eq 'python org-babel-python-mode)
  120. (fboundp 'run-python)) ; python.el
  121. (run-python))
  122. ((and (eq 'python-mode org-babel-python-mode)
  123. (fboundp 'py-shell)) ; python-mode.el
  124. ;; Make sure that py-which-bufname is initialized, as otherwise
  125. ;; it will be overwritten the first time a Python buffer is
  126. ;; created.
  127. (py-toggle-shells py-default-interpreter)
  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 (and python-buffer (buffer-live-p 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. "A string to indicate that evaluation 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. (session body &optional result-type result-params preamble)
  163. "Evaluate BODY as python code."
  164. (if session
  165. (org-babel-python-evaluate-session
  166. session body result-type result-params)
  167. (org-babel-python-evaluate-external-process
  168. body result-type result-params preamble)))
  169. (defun org-babel-python-evaluate-external-process
  170. (body &optional result-type result-params preamble)
  171. "Evaluate BODY in external python process.
  172. If RESULT-TYPE equals 'output then return standard output as a
  173. string. If RESULT-TYPE equals 'value then return the value of the
  174. last statement in BODY, as elisp."
  175. ((lambda (raw)
  176. (if (or (member "code" result-params)
  177. (member "pp" result-params)
  178. (and (member "output" result-params)
  179. (not (member "table" result-params))))
  180. raw
  181. (org-babel-python-table-or-string (org-babel-trim raw))))
  182. (case result-type
  183. (output (org-babel-eval org-babel-python-command
  184. (concat (if preamble (concat preamble "\n") "")
  185. body)))
  186. (value (let ((tmp-file (org-babel-temp-file "python-")))
  187. (org-babel-eval
  188. org-babel-python-command
  189. (concat
  190. (if preamble (concat preamble "\n") "")
  191. (format
  192. (if (member "pp" result-params)
  193. org-babel-python-pp-wrapper-method
  194. org-babel-python-wrapper-method)
  195. (mapconcat
  196. (lambda (line) (format "\t%s" line))
  197. (split-string
  198. (org-remove-indentation
  199. (org-babel-trim body))
  200. "[\r\n]") "\n")
  201. (org-babel-process-file-name tmp-file 'noquote))))
  202. (org-babel-eval-read-file tmp-file))))))
  203. (defun org-babel-python-evaluate-session
  204. (session body &optional result-type result-params)
  205. "Pass BODY to the Python process in SESSION.
  206. If RESULT-TYPE equals 'output then return standard output as a
  207. string. If RESULT-TYPE equals 'value then return the value of the
  208. last statement in BODY, as elisp."
  209. (flet ((send-wait () (comint-send-input nil t) (sleep-for 0 5))
  210. (dump-last-value
  211. (tmp-file pp)
  212. (mapc
  213. (lambda (statement) (insert statement) (send-wait))
  214. (if pp
  215. (list
  216. "import pprint"
  217. (format "open('%s', 'w').write(pprint.pformat(_))"
  218. (org-babel-process-file-name tmp-file 'noquote)))
  219. (list (format "open('%s', 'w').write(str(_))"
  220. (org-babel-process-file-name tmp-file 'noquote))))))
  221. (input-body (body)
  222. (mapc (lambda (line) (insert line) (send-wait))
  223. (split-string body "[\r\n]"))
  224. (send-wait)))
  225. ((lambda (results)
  226. (unless (string= (substring org-babel-python-eoe-indicator 1 -1) results)
  227. (if (or (member "code" result-params)
  228. (member "pp" result-params)
  229. (and (member "output" result-params)
  230. (not (member "table" result-params))))
  231. results
  232. (org-babel-python-table-or-string results))))
  233. (case result-type
  234. (output
  235. (mapconcat
  236. #'org-babel-trim
  237. (butlast
  238. (org-babel-comint-with-output
  239. (session org-babel-python-eoe-indicator t body)
  240. (input-body body)
  241. (send-wait) (send-wait)
  242. (insert org-babel-python-eoe-indicator)
  243. (send-wait))
  244. 2) "\n"))
  245. (value
  246. (let ((tmp-file (org-babel-temp-file "python-")))
  247. (org-babel-comint-with-output
  248. (session org-babel-python-eoe-indicator nil body)
  249. (let ((comint-process-echoes nil))
  250. (input-body body)
  251. (dump-last-value tmp-file (member "pp" result-params))
  252. (send-wait) (send-wait)
  253. (insert org-babel-python-eoe-indicator)
  254. (send-wait)))
  255. (org-babel-eval-read-file tmp-file)))))))
  256. (defun org-babel-python-read-string (string)
  257. "Strip 's from around python string"
  258. (if (string-match "^'\\([^\000]+\\)'$" string)
  259. (match-string 1 string)
  260. string))
  261. (provide 'ob-python)
  262. ;;; ob-python.el ends here