1

Using python cmd module, I would like to be able to quit the command line application using Ctrl+D. However, default behavior prints ^D instead of quitting the application.

Reading the documentation, I can't seem to find a way to do it. Any hints ?

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
Overdrivr
  • 6,296
  • 5
  • 44
  • 70

1 Answers1

3

From the doc:

An end-of-file on input is passed back as the string 'EOF'.

Which means that Ctrl+D is dispatched to the do_EOF() method. So to give a way to exit your interpreter, make sure to implement do_EOF() and have it return True:

def do_EOF(self, line):
    return True
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • Sorry for the late comment. When I type `Ctrl+D` it just prints `^D`. Using `Ctrl+C` exits the application, but without calling do_EOF. Any hints ? – Overdrivr May 25 '16 at 14:45
  • @Overdrivr: Have you overriden any of `Cmd`'s methods? If yes, you'd need to post the relevant code; if not, `Ctrl+D` should work after you add the above `do_EOF` method to your `Cmd` subclass (I've just tested it myself and it works). – Eugene Yarmash May 25 '16 at 15:35
  • Good point, hitting Ctrl+D should raise a KeyboardInterrupt or SystemExit exception is this correct ? – Overdrivr May 25 '16 at 19:53
  • @Overdrivr: `EOFError`, I guess. But this is catched and handled by `cmd` anyway (by dispatching to `do_EOF()`). – Eugene Yarmash May 26 '16 at 12:21