org-babel-python.el 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. (add-to-list 'org-babel-tangle-langs '("python" "py" "#!/usr/bin/env python"))
  29. (defun org-babel-execute:python (body params)
  30. "Execute a block of Python code with org-babel. This function is
  31. called by `org-babel-execute-src-block' via multiple-value-bind."
  32. (message "executing Python source code block")
  33. (let ((full-body (concat
  34. (mapconcat ;; define any variables
  35. (lambda (pair)
  36. (format "%s=%s"
  37. (car pair)
  38. (org-babel-python-var-to-python (cdr pair))))
  39. vars "\n") "\n" (org-babel-trim body) "\n")) ;; then the source block body
  40. (session (org-babel-python-initiate-session session)))
  41. (org-babel-python-evaluate session full-body result-type)))
  42. (defun org-babel-prep-session:python (session params)
  43. "Prepare SESSION according to the header arguments specified in PARAMS."
  44. (let* ((session (org-babel-python-initiate-session session))
  45. (vars (org-babel-ref-variables params))
  46. (var-lines (mapcar ;; define any variables
  47. (lambda (pair)
  48. (format "%s=%s"
  49. (car pair)
  50. (org-babel-python-var-to-python (cdr pair))))
  51. vars)))
  52. (org-babel-comint-in-buffer session
  53. (mapc (lambda (var)
  54. (move-end-of-line 1) (insert var) (comint-send-input nil t)
  55. (org-babel-comint-wait-for-output session)) var-lines))))
  56. ;; helper functions
  57. (defun org-babel-python-var-to-python (var)
  58. "Convert an elisp var into a string of python source code
  59. specifying a var of the same value."
  60. (if (listp var)
  61. (concat "[" (mapconcat #'org-babel-python-var-to-python var ", ") "]")
  62. (format "%S" var)))
  63. (defun org-babel-python-table-or-string (results)
  64. "If the results look like a table, then convert them into an
  65. Emacs-lisp table, otherwise return the results as a string."
  66. (org-babel-read
  67. (if (string-match "^\\[.+\\]$" results)
  68. (org-babel-read
  69. (replace-regexp-in-string
  70. "\\[" "(" (replace-regexp-in-string
  71. "\\]" ")" (replace-regexp-in-string
  72. ", " " " (replace-regexp-in-string
  73. "'" "\"" results)))))
  74. results)))
  75. (defvar org-babel-python-buffers '(:default . nil))
  76. (defun org-babel-python-session-buffer (session)
  77. (cdr (assoc session org-babel-python-buffers)))
  78. (defun org-babel-python-initiate-session-by-key (&optional session)
  79. "If there is not a current inferior-process-buffer in SESSION
  80. then create. Return the initialized session."
  81. (save-window-excursion
  82. (let* ((session (if session (intern session) :default))
  83. (python-buffer (org-babel-python-session-buffer session)))
  84. (run-python)
  85. (setq org-babel-python-buffers (cons (cons session python-buffer)
  86. (assq-delete-all session org-babel-python-buffers)))
  87. session)))
  88. (defun org-babel-python-initiate-session (&optional session)
  89. (unless (string= session "none")
  90. (org-babel-python-session-buffer (org-babel-python-initiate-session-by-key session))))
  91. (defvar org-babel-python-last-value-eval "_"
  92. "When evaluated by Python this returns the return value of the last statement.")
  93. (defvar org-babel-python-eoe-indicator "'org_babel_python_eoe'"
  94. "Used to indicate that evaluation is has completed.")
  95. (defvar org-babel-python-wrapper-method
  96. "
  97. def main():
  98. %s
  99. open('%s', 'w').write( str(main()) )")
  100. (defun org-babel-python-evaluate (buffer body &optional result-type)
  101. "Pass BODY to the Python process in BUFFER. If RESULT-TYPE equals
  102. 'output then return a list of the outputs of the statements in
  103. BODY, if RESULT-TYPE equals 'value then return the value of the
  104. last statement in BODY, as elisp."
  105. (if (not session)
  106. ;; external process evaluation
  107. (save-window-excursion
  108. (case result-type
  109. (output
  110. (with-temp-buffer
  111. (insert body)
  112. ;; (message "buffer=%s" (buffer-string)) ;; debugging
  113. (shell-command-on-region (point-min) (point-max) "python" 'replace)
  114. (buffer-string)))
  115. (value
  116. (let ((tmp-file (make-temp-file "python-functional-results")))
  117. (with-temp-buffer
  118. (insert
  119. (format
  120. org-babel-python-wrapper-method
  121. (let ((lines (split-string
  122. (org-remove-indentation (org-babel-trim body)) "[\r\n]")))
  123. (concat
  124. (mapconcat
  125. (lambda (line) (format "\t%s" line))
  126. (butlast lines) "\n")
  127. (format "\n\treturn %s" (last lines))))
  128. tmp-file))
  129. ;; (message "buffer=%s" (buffer-string)) ;; debugging
  130. (shell-command-on-region (point-min) (point-max) "python"))
  131. (org-babel-python-table-or-string
  132. (with-temp-buffer (insert-file-contents tmp-file) (buffer-string)))))))
  133. ;; comint session evaluation
  134. (org-babel-comint-in-buffer buffer
  135. (let* ((raw (org-babel-comint-with-output buffer org-babel-python-eoe-indicator t
  136. ;; for some reason python is fussy, and likes enters after every input
  137. (mapc (lambda (statement) (insert statement) (comint-send-input nil t))
  138. (split-string (org-babel-trim full-body) "[\r\n]+"))
  139. (comint-send-input nil t) (comint-send-input nil t)
  140. (insert org-babel-python-last-value-eval)
  141. (comint-send-input nil t)
  142. (insert org-babel-python-eoe-indicator)
  143. (comint-send-input nil t)))
  144. (results (delete org-babel-python-eoe-indicator
  145. (cdr (member org-babel-python-eoe-indicator
  146. (reverse (mapcar #'org-babel-trim raw)))))))
  147. (setq results (mapcar #'org-babel-python-read-string results))
  148. (case result-type
  149. (output (org-babel-trim (mapconcat #'identity (reverse (cdr results)) "\n")))
  150. (value (org-babel-python-table-or-string (org-babel-trim (car results)))))))))
  151. (defun org-babel-python-read-string (string)
  152. "Strip 's from around ruby string"
  153. (if (string-match "'\\([^\000]+\\)'" string)
  154. (match-string 1 string)
  155. string))
  156. (provide 'org-babel-python)
  157. ;;; org-babel-python.el ends here