Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using run-python on GNU Emacs 24.3 for its "Inferior python shell" and am trying to get behavior similar to lisp-send-last-sexp, that sends and evaluates an expression in the running interpreter. I'm only trying to do this for one line at a time.

I shortened the solutions given here to the following function:

(add-hook 'python-mode-hook
          'my-python-send-statement)

(defun my-python-send-statement ()
  (interactive)
  (local-set-key [S-return] 'my-python-send-statement)
  (end-of-line)
  (set-mark (line-beginning-position))
  (call-interactively 'python-shell-send-region))

It works, halfway. When I run this command down several lines, I get a string of several >>> prompts and I can't figure out why, as only one line should be sent. Also, sometimes the result won't be shown immediately, and I have to run the command twice. For example:

9+9 # run the command on line 13 of .py file,

======

# result in Python shell.

>>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> 18

share|improve this question
up vote 2 down vote accepted

DISCLAIMER: the following is self advertisement...

For managing interaction between a buffer and a code interpreter, I developed isend-mode.

Here is how you'd use it:

  1. Run a python interpreter in a terminal :

    M-xansi-termRET/usr/bin/pythonRET

  2. Switch to the buffer containing your python code :

    C-xbmy-buffer.pyRET

  3. Associate it with your terminal :

    M-xisendRET*ansi-term*RET

  4. Type C-RET to send the current buffer line to the interpreter.

The advantage of isend-mode (from my perspective, at least) is that it is language-agnostic. You can use it in the same way for python, shell, or whatever interpreted language which you like.

share|improve this answer

OK, after browsing the python-shell functions a bit more I put together a hack that solves my problem: send a print command after sending the region! For whatever reason this suppresses all the >>> prompts.

(add-hook 'python-mode-hook
          'my-python-send-statement)

(defun my-python-send-statement ()
  (interactive)
  (local-set-key [S-return] 'my-python-send-statement)
  (end-of-line)
  (set-mark (line-beginning-position))
  (call-interactively 'python-shell-send-region)
  (python-shell-send-string "; print()"))
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .