From d6496c8af8fc4c264e9ec87ac13d285d145241e2 Mon Sep 17 00:00:00 2001
From: Gary Oberbrunner <garyo@genarts.com>
Date: Wed, 20 Mar 2013 21:13:33 -0400
Subject: [PATCH] ob-python: fixes for session mode, buffer name and new
 python session command

 * Add new variable org-babel-python-session-command for use in session mode.
 * Set python session buffer name correctly.
---
 lisp/ob-python.el | 24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)

diff --git a/lisp/ob-python.el b/lisp/ob-python.el
index 7bc9a1f..7bd7bc4 100644
--- a/lisp/ob-python.el
+++ b/lisp/ob-python.el
@@ -47,6 +47,17 @@
   :group 'org-babel
   :type 'string)
 
+;;; This needs to be python -i for Windows at least,
+;;; since python without -i won't output a prompt, which
+;;; would hang ob-python.
+;;; Shouldn't hurt on other systems.
+(defcustom org-babel-python-session-command "python -i"
+  "Name of the command for executing Python code in session mode."
+  :version "24.4"
+  :package-version '(Org . "8.0")
+  :group 'org-babel
+  :type 'string)
+
 (defcustom org-babel-python-mode
   (if (or (featurep 'xemacs) (featurep 'python-mode)) 'python-mode 'python)
   "Preferred python mode for use in running python interactively.
@@ -169,9 +180,16 @@ then create.  Return the initialized session."
       (cond
        ((and (eq 'python org-babel-python-mode)
 	     (fboundp 'run-python)) ; python.el
-	(if (version< "24.1" emacs-version)
-	    (run-python org-babel-python-command)
-	  (run-python)))
+	;; run-python runs or switches to python in python-shell-buffer-name
+        ;; (with '*'s added at beginning and end)
+	;; so name the buffer after the session, zapping any leading/trailing *s
+	(let ((python-shell-buffer-name
+	       (replace-regexp-in-string ;; zap surrounding *
+		"^\\*\\([^*]+\\)\\*$" "\\1" (symbol-name session))))
+	  (if (version< "24.1" emacs-version)
+	      (run-python org-babel-python-session-command)
+	    (run-python))
+	  (setq python-buffer (concat "*" python-shell-buffer-name "*"))))
        ((and (eq 'python-mode org-babel-python-mode)
 	     (fboundp 'py-shell)) ; python-mode.el
 	;; Make sure that py-which-bufname is initialized, as otherwise
-- 
1.7.11.msysgit.1

