ob-python.el 16 KB

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