ob-python.el 12 KB

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