ob-python.el 13 KB

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