jj172
jj172

Reputation: 809

Python cmd.cmd exit on ctrl+D

How do you make CmdModule exit when issuing a ctrl+D command? By default, we have the shell exit when you issue a ctrl+C command, but does not exit when issuing ctrl+D.

Upvotes: 3

Views: 694

Answers (2)

Bond
Bond

Reputation: 16

Put a guard in the 'default' handler which acts upon the 'EOF' then it will not show up in help.

For example:

from cmd import Cmd


class MyShell(Cmd):
    intro = f"My interactive shell"
    prompt = "(shell) "

    def default(self, arg):
        "Fallback handler for commands."
        if arg == "EOF":
            print("\r")
            return True
        # The rest of your default handler code if required.
        pass

    def do_echo(self, arg):
        "Echo the supplied argument."
        print(arg)

    def do_q(self, arg):
        "Quits the shell."
        exit(0)


if __name__ == "__main__":
    MyShell().cmdloop()

Upvotes: 0

jj172
jj172

Reputation: 809

From https://pymotw.com/3/cmd/, it seems like we just implement:

def do_EOF(self, line):
        return True

in the main class, and this do_EOF function handles this ctrl+D output.

Edit:

Note that this will also cause it to exit if you type the command "EOF". It will also cause "EOF" to show up in your help command.

Upvotes: 4

Related Questions