Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending code from Python buffer to IPython session running from M-x ansi-term

Say I open a terminal emulator in Emacs with M-x ansi-term. This opens a buffer in Emacs with the shell of my choice. Say I then run ipython from this shell. Can I send code to this ipython session from another buffer with Python code in Emacs? If so how?

like image 577
Amelio Vazquez-Reina Avatar asked Sep 23 '26 04:09

Amelio Vazquez-Reina


2 Answers

I have a minor mode for this purpose (except it is not IPython-specific and I mostly use it for shell scripts): isend-mode.

Here is how you would use it:

  1. Open an ansi-term buffer:

    M-xansi-termRET/usr/bin/ipythonRET

  2. Open the buffer with the code you want to execute, and associate it to the interpreter buffer:

    M-xisend-associateRET*ansi-term*RET

  3. Hit C-RET in the python buffer to send the current line to the interpreter in the ansi-term buffer.

like image 65
François Févotte Avatar answered Sep 25 '26 03:09

François Févotte


(defun send-buffer-to-ipython ()
  "Send current buffer to the running ipython process."
  (interactive)
  (let* ((ipython-buffer "*ansi-term*") ; the buffer name of your running terminal
         (proc (get-buffer-process ipython-buffer)))
    (unless proc
      (error "no process found"))
    (save-buffer)
    (process-send-string proc
                         (format "execfile(\"%s\")\n" (buffer-file-name)))
    (pop-to-buffer ipython-buffer)      ; show ipython and select it
    ;; (display-buffer ipython-buffer)  ; show ipython but don't select it
    ))

Then bind command send-buffer-to-ipython to any key you like. I bind it to C-c C-c

(define-key python-mode-map [?\C-c ?\C-c] 'send-buffer-to-ipython)
like image 35
Tao Peng Avatar answered Sep 25 '26 03:09

Tao Peng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!