ob-python.el 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. ;;; ob-python.el --- Babel Functions for Python -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2022 Free Software Foundation, Inc.
  3. ;; Authors: Eric Schulte
  4. ;; Dan Davison
  5. ;; Maintainer: Jack Kamm <jackkamm@gmail.com>
  6. ;; Keywords: literate programming, reproducible research
  7. ;; Homepage: https://orgmode.org
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;; Org-Babel support for evaluating python source code.
  21. ;;; Code:
  22. (require 'ob)
  23. (require 'org-macs)
  24. (require 'python)
  25. (declare-function py-shell "ext:python-mode" (&rest args))
  26. (declare-function py-toggle-shells "ext:python-mode" (arg))
  27. (declare-function py-shell-send-string "ext:python-mode" (strg &optional process))
  28. (defvar org-babel-tangle-lang-exts)
  29. (add-to-list 'org-babel-tangle-lang-exts '("python" . "py"))
  30. (defvar org-babel-default-header-args:python '())
  31. (defcustom org-babel-python-command "python"
  32. "Name of the command for executing Python code."
  33. :version "24.4"
  34. :package-version '(Org . "8.0")
  35. :group 'org-babel
  36. :type 'string)
  37. (defcustom org-babel-python-mode
  38. (if (featurep 'python-mode) 'python-mode 'python)
  39. "Preferred python mode for use in running python interactively.
  40. This will typically be either `python' or `python-mode'."
  41. :group 'org-babel
  42. :version "24.4"
  43. :package-version '(Org . "8.0")
  44. :type 'symbol)
  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 'symbol)
  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* ((org-babel-python-command
  61. (or (cdr (assq :python params))
  62. org-babel-python-command))
  63. (session (org-babel-python-initiate-session
  64. (cdr (assq :session params))))
  65. (result-params (cdr (assq :result-params params)))
  66. (result-type (cdr (assq :result-type params)))
  67. (return-val (when (eq result-type 'value)
  68. (cdr (assq :return params))))
  69. (preamble (cdr (assq :preamble params)))
  70. (async (org-babel-comint-use-async params))
  71. (full-body
  72. (concat
  73. (org-babel-expand-body:generic
  74. body params
  75. (org-babel-variable-assignments:python params))
  76. (when return-val
  77. (format (if session "\n%s" "\nreturn %s") return-val))))
  78. (result (org-babel-python-evaluate
  79. session full-body result-type
  80. result-params preamble async)))
  81. (org-babel-reassemble-table
  82. result
  83. (org-babel-pick-name (cdr (assq :colname-names params))
  84. (cdr (assq :colnames params)))
  85. (org-babel-pick-name (cdr (assq :rowname-names params))
  86. (cdr (assq :rownames params))))))
  87. (defun org-babel-prep-session:python (session params)
  88. "Prepare SESSION according to the header arguments in PARAMS.
  89. VARS contains resolved variable references."
  90. (let* ((session (org-babel-python-initiate-session session))
  91. (var-lines
  92. (org-babel-variable-assignments:python params)))
  93. (org-babel-comint-in-buffer session
  94. (mapc (lambda (var)
  95. (end-of-line 1) (insert var) (comint-send-input)
  96. (org-babel-comint-wait-for-output session))
  97. var-lines))
  98. session))
  99. (defun org-babel-load-session:python (session body params)
  100. "Load BODY into SESSION."
  101. (save-window-excursion
  102. (let ((buffer (org-babel-prep-session:python session params)))
  103. (with-current-buffer buffer
  104. (goto-char (process-mark (get-buffer-process (current-buffer))))
  105. (insert (org-babel-chomp body)))
  106. buffer)))
  107. ;; helper functions
  108. (defun org-babel-variable-assignments:python (params)
  109. "Return a list of Python statements assigning the block's variables."
  110. (mapcar
  111. (lambda (pair)
  112. (format "%s=%s"
  113. (car pair)
  114. (org-babel-python-var-to-python (cdr pair))))
  115. (org-babel--get-vars params)))
  116. (defun org-babel-python-var-to-python (var)
  117. "Convert an elisp value to a python variable.
  118. Convert an elisp value, VAR, into a string of python source code
  119. specifying a variable of the same value."
  120. (if (listp var)
  121. (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
  122. (if (eq var 'hline)
  123. org-babel-python-hline-to
  124. (format
  125. (if (and (stringp var) (string-match "[\n\r]" var)) "\"\"%S\"\"" "%S")
  126. (if (stringp var) (substring-no-properties var) var)))))
  127. (defun org-babel-python-table-or-string (results)
  128. "Convert RESULTS into an appropriate elisp value.
  129. If the results look like a list or tuple, then convert them into an
  130. Emacs-lisp table, otherwise return the results as a string."
  131. (let ((res (org-babel-script-escape results)))
  132. (if (listp res)
  133. (mapcar (lambda (el) (if (eq el 'None)
  134. org-babel-python-None-to el))
  135. res)
  136. res)))
  137. (defvar org-babel-python-buffers '((:default . "*Python*")))
  138. (defun org-babel-python-session-buffer (session)
  139. "Return the buffer associated with SESSION."
  140. (cdr (assoc session org-babel-python-buffers)))
  141. (defun org-babel-python-with-earmuffs (session)
  142. (let ((name (if (stringp session) session (format "%s" session))))
  143. (if (and (string= "*" (substring name 0 1))
  144. (string= "*" (substring name (- (length name) 1))))
  145. name
  146. (format "*%s*" name))))
  147. (defun org-babel-python-without-earmuffs (session)
  148. (let ((name (if (stringp session) session (format "%s" session))))
  149. (if (and (string= "*" (substring name 0 1))
  150. (string= "*" (substring name (- (length name) 1))))
  151. (substring name 1 (- (length name) 1))
  152. name)))
  153. (defvar py-default-interpreter)
  154. (defvar py-which-bufname)
  155. (defvar python-shell-buffer-name)
  156. (defun org-babel-python-initiate-session-by-key (&optional session)
  157. "Initiate a python session.
  158. If there is not a current inferior-process-buffer in SESSION
  159. then create. Return the initialized session."
  160. (save-window-excursion
  161. (let* ((session (if session (intern session) :default))
  162. (py-buffer (org-babel-python-session-buffer session))
  163. (cmd (if (member system-type '(cygwin windows-nt ms-dos))
  164. (concat org-babel-python-command " -i")
  165. org-babel-python-command)))
  166. (cond
  167. ((eq 'python org-babel-python-mode) ; python.el
  168. (unless py-buffer
  169. (setq py-buffer (org-babel-python-with-earmuffs session)))
  170. (let ((python-shell-buffer-name
  171. (org-babel-python-without-earmuffs py-buffer)))
  172. (run-python cmd)
  173. (sleep-for 0 10)))
  174. ((and (eq 'python-mode org-babel-python-mode)
  175. (fboundp 'py-shell)) ; python-mode.el
  176. (require 'python-mode)
  177. ;; Make sure that py-which-bufname is initialized, as otherwise
  178. ;; it will be overwritten the first time a Python buffer is
  179. ;; created.
  180. (py-toggle-shells py-default-interpreter)
  181. ;; `py-shell' creates a buffer whose name is the value of
  182. ;; `py-which-bufname' with '*'s at the beginning and end
  183. (let* ((bufname (if (and py-buffer (buffer-live-p py-buffer))
  184. (replace-regexp-in-string ;; zap surrounding *
  185. "^\\*\\([^*]+\\)\\*$" "\\1" py-buffer)
  186. (concat "Python-" (symbol-name session))))
  187. (py-which-bufname bufname))
  188. (setq py-buffer (org-babel-python-with-earmuffs bufname))
  189. (py-shell nil nil t org-babel-python-command py-buffer nil nil t nil)))
  190. (t
  191. (error "No function available for running an inferior Python")))
  192. (setq org-babel-python-buffers
  193. (cons (cons session py-buffer)
  194. (assq-delete-all session org-babel-python-buffers)))
  195. session)))
  196. (defun org-babel-python-initiate-session (&optional session _params)
  197. "Create a session named SESSION according to PARAMS."
  198. (unless (string= session "none")
  199. (org-babel-python-session-buffer
  200. (org-babel-python-initiate-session-by-key session))))
  201. (defvar org-babel-python-eoe-indicator "org_babel_python_eoe"
  202. "A string to indicate that evaluation has completed.")
  203. (defconst org-babel-python-wrapper-method
  204. "
  205. def main():
  206. %s
  207. open('%s', 'w').write( str(main()) )")
  208. (defconst org-babel-python-pp-wrapper-method
  209. "
  210. import pprint
  211. def main():
  212. %s
  213. open('%s', 'w').write( pprint.pformat(main()) )")
  214. (defconst org-babel-python--exec-tmpfile "\
  215. with open('%s') as __org_babel_python_tmpfile:
  216. exec(compile(__org_babel_python_tmpfile.read(), __org_babel_python_tmpfile.name, 'exec'))"
  217. "Template for Python session command with output results.
  218. Has a single %s escape, the tempfile containing the source code
  219. to evaluate.")
  220. (defun org-babel-python-format-session-value
  221. (src-file result-file result-params)
  222. "Return Python code to evaluate SRC-FILE and write result to RESULT-FILE."
  223. (format "\
  224. import ast
  225. with open('%s') as __org_babel_python_tmpfile:
  226. __org_babel_python_ast = ast.parse(__org_babel_python_tmpfile.read())
  227. __org_babel_python_final = __org_babel_python_ast.body[-1]
  228. if isinstance(__org_babel_python_final, ast.Expr):
  229. __org_babel_python_ast.body = __org_babel_python_ast.body[:-1]
  230. exec(compile(__org_babel_python_ast, '<string>', 'exec'))
  231. __org_babel_python_final = eval(compile(ast.Expression(
  232. __org_babel_python_final.value), '<string>', 'eval'))
  233. with open('%s', 'w') as __org_babel_python_tmpfile:
  234. if %s:
  235. import pprint
  236. __org_babel_python_tmpfile.write(pprint.pformat(__org_babel_python_final))
  237. else:
  238. __org_babel_python_tmpfile.write(str(__org_babel_python_final))
  239. else:
  240. exec(compile(__org_babel_python_ast, '<string>', 'exec'))
  241. __org_babel_python_final = None"
  242. (org-babel-process-file-name src-file 'noquote)
  243. (org-babel-process-file-name result-file 'noquote)
  244. (if (member "pp" result-params) "True" "False")))
  245. (defun org-babel-python-evaluate
  246. (session body &optional result-type result-params preamble async)
  247. "Evaluate BODY as Python code."
  248. (if session
  249. (if async
  250. (org-babel-python-async-evaluate-session
  251. session body result-type result-params)
  252. (org-babel-python-evaluate-session
  253. session body result-type result-params))
  254. (org-babel-python-evaluate-external-process
  255. body result-type result-params preamble)))
  256. (defun org-babel-python--shift-right (body &optional count)
  257. (with-temp-buffer
  258. (python-mode)
  259. (insert body)
  260. (goto-char (point-min))
  261. (while (not (eobp))
  262. (unless (python-syntax-context 'string)
  263. (python-indent-shift-right (line-beginning-position)
  264. (line-end-position)
  265. count))
  266. (forward-line 1))
  267. (buffer-string)))
  268. (defun org-babel-python-evaluate-external-process
  269. (body &optional result-type result-params preamble)
  270. "Evaluate BODY in external python process.
  271. If RESULT-TYPE equals `output' then return standard output as a
  272. string. If RESULT-TYPE equals `value' then return the value of the
  273. last statement in BODY, as elisp."
  274. (let ((raw
  275. (pcase result-type
  276. (`output (org-babel-eval org-babel-python-command
  277. (concat preamble (and preamble "\n")
  278. body)))
  279. (`value (let ((tmp-file (org-babel-temp-file "python-")))
  280. (org-babel-eval
  281. org-babel-python-command
  282. (concat
  283. preamble (and preamble "\n")
  284. (format
  285. (if (member "pp" result-params)
  286. org-babel-python-pp-wrapper-method
  287. org-babel-python-wrapper-method)
  288. (org-babel-python--shift-right body)
  289. (org-babel-process-file-name tmp-file 'noquote))))
  290. (org-babel-eval-read-file tmp-file))))))
  291. (org-babel-result-cond result-params
  292. raw
  293. (org-babel-python-table-or-string (org-trim raw)))))
  294. (defun org-babel-python--send-string (session body)
  295. "Pass BODY to the Python process in SESSION.
  296. Return output."
  297. (with-current-buffer session
  298. (let* ((string-buffer "")
  299. (comint-output-filter-functions
  300. (cons (lambda (text) (setq string-buffer
  301. (concat string-buffer text)))
  302. comint-output-filter-functions))
  303. (body (format "\
  304. try:
  305. %s
  306. except:
  307. raise
  308. finally:
  309. print('%s')"
  310. (org-babel-python--shift-right body 4)
  311. org-babel-python-eoe-indicator)))
  312. (if (not (eq 'python-mode org-babel-python-mode))
  313. (let ((python-shell-buffer-name
  314. (org-babel-python-without-earmuffs session)))
  315. (python-shell-send-string body))
  316. (require 'python-mode)
  317. (py-shell-send-string body (get-buffer-process session)))
  318. ;; same as `python-shell-comint-end-of-output-p' in emacs-25.1+
  319. (while (not (string-match
  320. org-babel-python-eoe-indicator
  321. string-buffer))
  322. (accept-process-output (get-buffer-process (current-buffer))))
  323. (org-babel-chomp (substring string-buffer 0 (match-beginning 0))))))
  324. (defun org-babel-python-evaluate-session
  325. (session body &optional result-type result-params)
  326. "Pass BODY to the Python process in SESSION.
  327. If RESULT-TYPE equals `output' then return standard output as a
  328. string. If RESULT-TYPE equals `value' then return the value of the
  329. last statement in BODY, as elisp."
  330. (let* ((tmp-src-file (org-babel-temp-file "python-"))
  331. (results
  332. (progn
  333. (with-temp-file tmp-src-file (insert body))
  334. (pcase result-type
  335. (`output
  336. (let ((body (format org-babel-python--exec-tmpfile
  337. (org-babel-process-file-name
  338. tmp-src-file 'noquote))))
  339. (org-babel-python--send-string session body)))
  340. (`value
  341. (let* ((tmp-results-file (org-babel-temp-file "python-"))
  342. (body (org-babel-python-format-session-value
  343. tmp-src-file tmp-results-file result-params)))
  344. (org-babel-python--send-string session body)
  345. (sleep-for 0 10)
  346. (org-babel-eval-read-file tmp-results-file)))))))
  347. (org-babel-result-cond result-params
  348. results
  349. (org-babel-python-table-or-string results))))
  350. (defun org-babel-python-read-string (string)
  351. "Strip \\='s from around Python string."
  352. (if (and (string-prefix-p "'" string)
  353. (string-suffix-p "'" string))
  354. (substring string 1 -1)
  355. string))
  356. ;; Async session eval
  357. (defconst org-babel-python-async-indicator "print ('ob_comint_async_python_%s_%s')")
  358. (defun org-babel-python-async-value-callback (params tmp-file)
  359. (let ((result-params (cdr (assq :result-params params)))
  360. (results (org-babel-eval-read-file tmp-file)))
  361. (org-babel-result-cond result-params
  362. results
  363. (org-babel-python-table-or-string results))))
  364. (defun org-babel-python-async-evaluate-session
  365. (session body &optional result-type result-params)
  366. "Asynchronously evaluate BODY in SESSION.
  367. Returns a placeholder string for insertion, to later be replaced
  368. by `org-babel-comint-async-filter'."
  369. (org-babel-comint-async-register
  370. session (current-buffer)
  371. "ob_comint_async_python_\\(.+\\)_\\(.+\\)"
  372. 'org-babel-chomp 'org-babel-python-async-value-callback)
  373. (let ((python-shell-buffer-name (org-babel-python-without-earmuffs session)))
  374. (pcase result-type
  375. (`output
  376. (let ((uuid (md5 (number-to-string (random 100000000)))))
  377. (with-temp-buffer
  378. (insert (format org-babel-python-async-indicator "start" uuid))
  379. (insert "\n")
  380. (insert body)
  381. (insert "\n")
  382. (insert (format org-babel-python-async-indicator "end" uuid))
  383. (python-shell-send-buffer))
  384. uuid))
  385. (`value
  386. (let ((tmp-results-file (org-babel-temp-file "python-"))
  387. (tmp-src-file (org-babel-temp-file "python-")))
  388. (with-temp-file tmp-src-file (insert body))
  389. (with-temp-buffer
  390. (insert (org-babel-python-format-session-value tmp-src-file tmp-results-file result-params))
  391. (insert "\n")
  392. (insert (format org-babel-python-async-indicator "file" tmp-results-file))
  393. (python-shell-send-buffer))
  394. tmp-results-file)))))
  395. (provide 'ob-python)
  396. ;;; ob-python.el ends here