ob-python.el 14 KB

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