ob-python.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. ;;; ob-python.el --- Babel Functions for Python -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2019 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. (require 'org-macs)
  23. (declare-function py-shell "ext:python-mode" (&optional argprompt))
  24. (declare-function py-toggle-shells "ext:python-mode" (arg))
  25. (declare-function run-python "ext:python" (&optional cmd dedicated show))
  26. (defvar org-babel-tangle-lang-exts)
  27. (add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
  28. (defvar org-babel-default-header-args:python '())
  29. (defcustom org-babel-python-command "python"
  30. "Name of the command for executing Python code."
  31. :version "24.4"
  32. :package-version '(Org . "8.0")
  33. :group 'org-babel
  34. :type 'string)
  35. (defcustom org-babel-python-mode
  36. (if (featurep 'python-mode) 'python-mode 'python)
  37. "Preferred python mode for use in running python interactively.
  38. This will typically be either `python' or `python-mode'."
  39. :group 'org-babel
  40. :version "24.4"
  41. :package-version '(Org . "8.0")
  42. :type 'symbol)
  43. (defcustom org-babel-python-hline-to "None"
  44. "Replace hlines in incoming tables with this when translating to python."
  45. :group 'org-babel
  46. :version "24.4"
  47. :package-version '(Org . "8.0")
  48. :type 'string)
  49. (defcustom org-babel-python-None-to 'hline
  50. "Replace `None' in python tables with this before returning."
  51. :group 'org-babel
  52. :version "24.4"
  53. :package-version '(Org . "8.0")
  54. :type 'symbol)
  55. (defun org-babel-execute:python (body params)
  56. "Execute a block of Python code with Babel.
  57. This function is called by `org-babel-execute-src-block'."
  58. (let* ((org-babel-python-command
  59. (or (cdr (assq :python params))
  60. org-babel-python-command))
  61. (session (org-babel-python-initiate-session
  62. (cdr (assq :session params))))
  63. (result-params (cdr (assq :result-params params)))
  64. (result-type (cdr (assq :result-type params)))
  65. (return-val (when (and (eq result-type 'value) (not session))
  66. (cdr (assq :return params))))
  67. (preamble (cdr (assq :preamble params)))
  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. (defconst org-babel-python--exec-tmpfile
  209. (concat
  210. "__org_babel_python_fname = '%s'; "
  211. "__org_babel_python_fh = open(__org_babel_python_fname); "
  212. "exec(compile("
  213. "__org_babel_python_fh.read(), __org_babel_python_fname, 'exec'"
  214. ")); "
  215. "__org_babel_python_fh.close()"))
  216. (defun org-babel-python-evaluate
  217. (session body &optional result-type result-params preamble)
  218. "Evaluate BODY as Python code."
  219. (if session
  220. (org-babel-python-evaluate-session
  221. session body result-type result-params)
  222. (org-babel-python-evaluate-external-process
  223. body result-type result-params preamble)))
  224. (defun org-babel-python-evaluate-external-process
  225. (body &optional result-type result-params preamble)
  226. "Evaluate BODY in external python process.
  227. If RESULT-TYPE equals `output' then return standard output as a
  228. string. If RESULT-TYPE equals `value' then return the value of the
  229. last statement in BODY, as elisp."
  230. (let ((raw
  231. (pcase result-type
  232. (`output (org-babel-eval org-babel-python-command
  233. (concat preamble (and preamble "\n")
  234. body)))
  235. (`value (let ((tmp-file (org-babel-temp-file "python-")))
  236. (org-babel-eval
  237. org-babel-python-command
  238. (concat
  239. preamble (and preamble "\n")
  240. (format
  241. (if (member "pp" result-params)
  242. org-babel-python-pp-wrapper-method
  243. org-babel-python-wrapper-method)
  244. (mapconcat
  245. (lambda (line) (format "\t%s" line))
  246. (split-string (org-remove-indentation (org-trim body))
  247. "[\r\n]")
  248. "\n")
  249. (org-babel-process-file-name tmp-file 'noquote))))
  250. (org-babel-eval-read-file tmp-file))))))
  251. (org-babel-result-cond result-params
  252. raw
  253. (org-babel-python-table-or-string (org-trim raw)))))
  254. (defun org-babel-python-evaluate-session
  255. (session body &optional result-type result-params)
  256. "Pass BODY to the Python process in SESSION.
  257. If RESULT-TYPE equals `output' then return standard output as a
  258. string. If RESULT-TYPE equals `value' then return the value of the
  259. last statement in BODY, as elisp."
  260. (let* ((send-wait (lambda () (comint-send-input nil t) (sleep-for 0 5)))
  261. (dump-last-value
  262. (lambda
  263. (tmp-file pp)
  264. (mapc
  265. (lambda (statement) (insert statement) (funcall send-wait))
  266. (if pp
  267. (list
  268. "import pprint"
  269. (format "open('%s', 'w').write(pprint.pformat(_))"
  270. (org-babel-process-file-name tmp-file 'noquote)))
  271. (list (format "open('%s', 'w').write(str(_))"
  272. (org-babel-process-file-name tmp-file
  273. 'noquote)))))))
  274. (last-indent 0)
  275. (input-body (lambda (body)
  276. (dolist (line (split-string body "[\r\n]"))
  277. ;; Insert a blank line to end an indent
  278. ;; block.
  279. (let ((curr-indent (string-match "\\S-" line)))
  280. (if curr-indent
  281. (progn
  282. (when (< curr-indent last-indent)
  283. (insert "")
  284. (funcall send-wait))
  285. (setq last-indent curr-indent))
  286. (setq last-indent 0)))
  287. (insert line)
  288. (funcall send-wait))
  289. (funcall send-wait)))
  290. (results
  291. (pcase result-type
  292. (`output
  293. (let ((body (if (string-match-p ".\n+." body) ; Multiline
  294. (let ((tmp-src-file (org-babel-temp-file
  295. "python-")))
  296. (with-temp-file tmp-src-file (insert body))
  297. (format org-babel-python--exec-tmpfile
  298. tmp-src-file))
  299. body)))
  300. (mapconcat
  301. #'org-trim
  302. (butlast
  303. (org-babel-comint-with-output
  304. (session org-babel-python-eoe-indicator t body)
  305. (funcall input-body body)
  306. (funcall send-wait) (funcall send-wait)
  307. (insert org-babel-python-eoe-indicator)
  308. (funcall send-wait))
  309. 2) "\n")))
  310. (`value
  311. (let ((tmp-file (org-babel-temp-file "python-")))
  312. (org-babel-comint-with-output
  313. (session org-babel-python-eoe-indicator nil body)
  314. (let ((comint-process-echoes nil))
  315. (funcall input-body body)
  316. (funcall dump-last-value tmp-file
  317. (member "pp" result-params))
  318. (funcall send-wait) (funcall send-wait)
  319. (insert org-babel-python-eoe-indicator)
  320. (funcall send-wait)))
  321. (org-babel-eval-read-file tmp-file))))))
  322. (unless (string= (substring org-babel-python-eoe-indicator 1 -1) results)
  323. (org-babel-result-cond result-params
  324. results
  325. (org-babel-python-table-or-string results)))))
  326. (defun org-babel-python-read-string (string)
  327. "Strip \\='s from around Python string."
  328. (if (and (string-prefix-p "'" string)
  329. (string-suffix-p "'" string))
  330. (substring string 1 -1)
  331. string))
  332. (provide 'ob-python)
  333. ;;; ob-python.el ends here