ob-python.el 14 KB

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