How to cancel interpreter command in emacs python-mode

If I mistype a command in the python intepreter, sometimes I just see .... For example if I type help(random.unif and press enter I cannot enter a new command. I have to exit emacs and start python and the interpreter again. Is there way to correct this?

Best answer

As Pavel Anossov explains, you want to send Python a CTRL-C to interrupt it.

But in emacs, by default, CTRL-C is a prefix key.

Fortunately, in most interactive-shell modes, including python-mode and the alternatives, hitting CTRL-C twice in a row sends a ctrl-C to the interpreter. Or, more technically, CTRL-CCTRL-C is bound to comint-interrupt-subjob. (You can, of course, run it any other way—even META-X comint-interrupt-subjob if you really want.) The result looks like this:

Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help(f
...   ^C ^C
KeyboardInterrupt
>>> 

Another alternative is to use the quoted-insert command, usually bound to CTRL-Q, and then hit CTRL-C. However, because this will not interrupt the usual line input, you will usually have to follow it with a newline. The result looks like this:

Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help(f
... ^C
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>>