2

How can I evaluate a line of Python code from emacs buffer and have the result be written to the buffer at my cursor? I want to do something like in haskell-mode where you can type C-u C-c C-t and the type definition of whatever was at your cursor is inserted at your cursor.

So, if I selected and sent a region such as

1 + 2

from a .py buffer to the Python inferior process I would then see

3 1 + 2

in my .py buffer, ie. the 3 followed by a newline was inserted at point.

2 Answers 2

1

To insert the result of a shell command at point we have C-u M-! (shell-command), so you can insert the result of a python command with python -c "print 1 + 2".

To take the current line would need a bit of lisp. Here a very simple example.

(defun my-py-eval-insert-current-line ()
     "Eval the current line and insert its result."
     (interactive)    
     (setq cmd (read-from-minibuffer "Python cmd: " (format "python -c 'print %s'" (current-line))))
     (setq res (shell-command-to-string cmd))
     (insert res)
     )

with

(defun current-line ()
"returns the current line."
;; http://ergoemacs.org/emacs/elisp_all_about_lines.html
     (let (p1 p2 myLine)
       (setq p1 (line-beginning-position) )
       (setq p2 (line-end-position) )
       (setq myLine (buffer-substring-no-properties p1 p2))
       ))

I would rather look at pymacs for something serious.

ps: elisp functions: http://wikemacs.org/wiki/Emacs_Lisp_Cheat_Sheet

Sign up to request clarification or add additional context in comments.

Comments

1

org-mode, i.e. org-babel provides a similar thing, which seems worth testing.

Current trunk of python-mode.el

https://launchpad.net/python-mode

offers an option py-store-result-p

When t, result is accessible in car of kill-ring - next yank inserts it.

You may define a command which reads (car kill-ring) for insert.

Also a feature request there should have some chances.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.