Cancel a "..." continuation block in Python interpreter

999 Views Asked by At

I often find myself in a situation like this:

>>> for line in infile.readlines():
...  line = line.rtrim()
...  line█      # ^^^^^ Oops, mistake!

At this point I want to start again (because I mixed up the "trim" from Java with the "strip" from Python). But I can't afford to let the loop run even one iteration, because it would mess with the file.

In this situation my typical way out is to type some illegal syntax, such as an exclamation mark:

>>> for line in infile.readlines():
...  line = line.rtrim()
...  line!
  File "<stdin>", line 2
    line!
        ^
SyntaxError: invalid syntax
>>> █

But that's a clumsy way of doing things, not pythonic at all. Isn't there some way to get the interpreter to forget the previous line of continuation that I typed in? That would also save me from retyping the whole thing again. Some control key combination? I can't find it.

1

There are 1 best solutions below

0
On

Under Linux (and MacOS?), Control-C will give you a KeyboardInterrupt:

>>> if True:
...     asdf
KeyboardInterrupt
>>> 

However, under Windows, that will throw you back to the command prompt. Control-D under Linux will get you back to the command prompt but only if you're on a blank line.

If your keyboard has a 'Home' key (or a shortcut for it such as function-left arrow under MacOS), you can quickly jump to the start of the line and add a '#' to comment out the line:

>>> if True:
... #   asdf
...     print(False)
...
False
>>>

The only downside to this is that it's a few more keystrokes. Both of these methods will lose your tabs/spaces and put you back at the start of the line.