org-babel-python.el 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. ;;; org-babel-python.el --- org-babel functions for python evaluation
  2. ;; Copyright (C) 2009 Eric Schulte
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 0.01
  7. ;;; License:
  8. ;; This program 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, or (at your option)
  11. ;; any later version.
  12. ;;
  13. ;; This program 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. ;;
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs; see the file COPYING. If not, write to the
  20. ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. ;; Boston, MA 02110-1301, USA.
  22. ;;; Commentary:
  23. ;; Org-Babel support for evaluating python source code.
  24. ;;; Code:
  25. (require 'org-babel)
  26. (require 'python)
  27. (org-babel-add-interpreter "python")
  28. (defun org-babel-execute:python (body params)
  29. "Execute a block of Python code with org-babel. This function is
  30. called by `org-babel-execute-src-block'."
  31. (message "executing Python source code block")
  32. (let* ((vars (org-babel-ref-variables params))
  33. (result-params (split-string (or (cdr (assoc :results params)) "")))
  34. (result-type (cond ((member "output" result-params) 'output)
  35. ((member "value" result-params) 'value)
  36. (t 'value)))
  37. (full-body (concat
  38. (mapconcat ;; define any variables
  39. (lambda (pair)
  40. (format "%s=%s"
  41. (car pair)
  42. (org-babel-python-var-to-python (cdr pair))))
  43. vars "\n") "\n" (org-babel-trim body) "\n")) ;; then the source block body
  44. (session (org-babel-python-initiate-session (cdr (assoc :session params))))
  45. (results (org-babel-python-evaluate session full-body result-type)))
  46. (if (member "scalar" result-params)
  47. results
  48. (setq results (case result-type ;; process results based on the result-type
  49. ('output (let ((tmp-file (make-temp-file "org-babel-python")))
  50. (with-temp-file tmp-file (insert results))
  51. (org-babel-import-elisp-from-file tmp-file)))
  52. ('value (org-babel-python-table-or-results results))))
  53. (if (and (member "vector" results) (not (listp results)))
  54. (list (list results))
  55. results))))
  56. (defun org-babel-prep-session:python (session params)
  57. "Prepare SESSION according to the header arguments specified in PARAMS."
  58. (let* ((session (org-babel-python-initiate-session session))
  59. (vars (org-babel-ref-variables params))
  60. (var-lines (mapcar ;; define any variables
  61. (lambda (pair)
  62. (format "%s=%s"
  63. (car pair)
  64. (org-babel-python-var-to-python (cdr pair))))
  65. vars)))
  66. (org-babel-comint-in-buffer session
  67. (mapc (lambda (var)
  68. (move-end-of-line 1) (insert var) (comint-send-input nil t)
  69. (org-babel-comint-wait-for-output session)) var-lines))))
  70. ;; helper functions
  71. (defun org-babel-python-var-to-python (var)
  72. "Convert an elisp var into a string of python source code
  73. specifying a var of the same value."
  74. (if (listp var)
  75. (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
  76. (format "%S" var)))
  77. (defun org-babel-python-table-or-results (results)
  78. "If the results look like a table, then convert them into an
  79. Emacs-lisp table, otherwise return the results as a string."
  80. (org-babel-read
  81. (if (string-match "^\\[.+\\]$" results)
  82. (org-babel-read
  83. (replace-regexp-in-string
  84. "\\[" "(" (replace-regexp-in-string
  85. "\\]" ")" (replace-regexp-in-string
  86. ", " " " (replace-regexp-in-string
  87. "'" "\"" results)))))
  88. results)))
  89. (defvar org-babel-python-buffers '(:default . nil))
  90. (defun org-babel-python-session-buffer (session)
  91. (cdr (assoc session org-babel-python-buffers)))
  92. (defun org-babel-python-initiate-session-by-key (&optional session)
  93. "If there is not a current inferior-process-buffer in SESSION
  94. then create. Return the initialized session."
  95. (save-window-excursion
  96. (let* ((session (if session (intern session) :default))
  97. (python-buffer (org-babel-python-session-buffer session)))
  98. (run-python)
  99. (setq org-babel-python-buffers (cons (cons session python-buffer) (assq-delete-all session org-babel-python-buffers)))
  100. session)))
  101. (defun org-babel-python-initiate-session (&optional session)
  102. (unless (string= session "none")
  103. (org-babel-python-session-buffer (org-babel-python-initiate-session-by-key session))))
  104. (defvar org-babel-python-last-value-eval "_"
  105. "When evaluated by Python this returns the return value of the last statement.")
  106. (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
  107. "Used to indicate that evaluation is has completed.")
  108. (defvar org-babel-python-wrapper-method
  109. "
  110. def main():
  111. %s
  112. open('%s', 'w').write( str(main()) )")
  113. (defun org-babel-python-evaluate (buffer body &optional result-type)
  114. "Pass BODY to the Python process in BUFFER. If RESULT-TYPE equals
  115. 'output then return a list of the outputs of the statements in
  116. BODY, if RESULT-TYPE equals 'value then return the value of the
  117. last statement in BODY."
  118. (if (not session)
  119. ;; external process evaluation
  120. (save-window-excursion
  121. (case result-type
  122. (output
  123. (with-temp-buffer
  124. (insert body)
  125. ;; (message "buffer=%s" (buffer-string)) ;; debugging
  126. (shell-command-on-region (point-min) (point-max) "python" 'replace)
  127. (buffer-string)))
  128. (value
  129. (let ((tmp-file (make-temp-file "python-functional-results")))
  130. (with-temp-buffer
  131. (insert (format org-babel-python-wrapper-method
  132. (let ((lines (split-string (org-remove-indentation (org-babel-trim body)) "[\r\n]")))
  133. (concat
  134. (mapconcat
  135. (lambda (line) (format "\t%s" line))
  136. (butlast lines) "\n")
  137. (format "\n\treturn %s" (last lines))))
  138. tmp-file))
  139. ;; (message "buffer=%s" (buffer-string)) ;; debugging
  140. (shell-command-on-region (point-min) (point-max) "python"))
  141. (with-temp-buffer (insert-file-contents tmp-file) (buffer-string))))))
  142. ;; comint session evaluation
  143. (org-babel-comint-in-buffer buffer
  144. (let* ((full-body (mapconcat #'org-babel-trim
  145. (list body org-babel-python-last-value-eval org-babel-python-eoe-indicator) "\n"))
  146. (raw (org-babel-comint-with-output buffer org-babel-python-eoe-indicator t
  147. ;; for some reason python is fussy, and likes enters after every input
  148. (mapc (lambda (statement) (insert statement) (comint-send-input nil t))
  149. (split-string full-body "[\r\n]+"))))
  150. (results (delete org-babel-python-eoe-indicator
  151. (cdr (member org-babel-python-eoe-indicator
  152. (reverse (mapcar #'org-babel-trim raw)))))))
  153. (setq results (mapcar #'org-babel-python-read-string results))
  154. (org-babel-trim (case result-type
  155. (output (mapconcat #'identity (reverse (cdr results)) "\n"))
  156. (value (car results))
  157. (t (reverse results))))))))
  158. (defun org-babel-python-read-string (string)
  159. "Strip 's from around ruby string"
  160. (if (string-match "'\\([^\000]+\\)'" string)
  161. (match-string 1 string)
  162. string))
  163. (provide 'org-babel-python)
  164. ;;; org-babel-python.el ends here