Function: org-babel-python-initiate-session-by-key

org-babel-python-initiate-session-by-key is a byte-compiled function defined in ob-python.el.gz.

Signature

(org-babel-python-initiate-session-by-key &optional SESSION)

Documentation

Initiate a python session.

If there is not a current inferior-process-buffer in SESSION then create. Return the initialized session.

Source Code

;; Defined in /usr/src/emacs/lisp/org/ob-python.el.gz
(defun org-babel-python-initiate-session-by-key (&optional session)
  "Initiate a python session.
If there is not a current inferior-process-buffer in SESSION
then create.  Return the initialized session."
  (save-window-excursion
    (let* ((session (if session (intern session) :default))
           (py-buffer (org-babel-python-session-buffer session))
	   (cmd (if (member system-type '(cygwin windows-nt ms-dos))
		    (concat org-babel-python-command " -i")
		  org-babel-python-command)))
      (cond
       ((eq 'python org-babel-python-mode) ; python.el
	(unless py-buffer
	  (setq py-buffer (org-babel-python-with-earmuffs session)))
	(let ((python-shell-buffer-name
	       (org-babel-python-without-earmuffs py-buffer)))
	  (run-python cmd)
          (with-current-buffer py-buffer
            (add-hook
             'python-shell-first-prompt-hook
             (lambda ()
               (setq-local org-babel-python--initialized t)
               (message "I am running!!!"))
             nil 'local))))
       ((and (eq 'python-mode org-babel-python-mode)
	     (fboundp 'py-shell)) ; python-mode.el
	(require 'python-mode)
	;; Make sure that py-which-bufname is initialized, as otherwise
	;; it will be overwritten the first time a Python buffer is
	;; created.
	(py-choose-shell)
	;; `py-shell' creates a buffer whose name is the value of
	;; `py-which-bufname' with '*'s at the beginning and end
	(let* ((bufname (if (and py-buffer (buffer-live-p py-buffer))
			    (replace-regexp-in-string ;; zap surrounding *
			     "^\\*\\([^*]+\\)\\*$" "\\1" py-buffer)
			  (concat "Python-" (symbol-name session))))
	       (py-which-bufname bufname))
	  (setq py-buffer (org-babel-python-with-earmuffs bufname))
	  (py-shell nil nil t org-babel-python-command py-buffer nil nil t nil)))
       (t
	(error "No function available for running an inferior Python")))
      ;; Wait until Python initializes.
      (if (eq 'python org-babel-python-mode) ; python.el
          ;; This is more reliable compared to
          ;; `org-babel-comint-wait-for-output' as python may emit
          ;; multiple prompts during initialization.
          (with-current-buffer py-buffer
            (while (not org-babel-python--initialized)
              (sleep-for 0 10)))
        (org-babel-comint-wait-for-output py-buffer))
      (setq org-babel-python-buffers
	    (cons (cons session py-buffer)
		  (assq-delete-all session org-babel-python-buffers)))
      session)))