ob-python.el 13 KB

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