2016-04-26 9 views
0

Ich habe ein Python-Programm, das die interaktive Python-Konsole einbetten muss.Exit code.InteractiveConsole(). Interact() ohne Hauptprogramm zu beenden

Ich bin derzeit InteractiveConsole von code Modul:

code.InteractiveConsole().interact()

Allerdings, wenn ich exit() in der Konsole geben, das gesamte Programm wird verlassen.

Wie kann ich die interaktive Konsole verlassen, ohne das Hauptprogramm zu beenden?

+0

Sie möchten vielleicht einen Blick darauf werfen. https://www.reddit.com/r/Python/comments/30i599/gracefully_break_out_of_codeinteractiveconsole/ –

+0

@PhillipMartin Vielen Dank! –

Antwort

1

Dank @PhillipMartin schaffte ich es zu tun, nachdem seine Verbindung zu lesen: https://www.reddit.com/r/Python/comments/30i599/gracefully_break_out_of_codeinteractiveconsole/

def console_exit(): 
    raise SystemExit 

try: 
    code.InteractiveConsole(locals={"exit": console_exit}).interact() 
except SystemExit: 
    pass 

# Continue doing stuff 

Auf diese Weise können exit in der Konsole erhöhen SystemExit nur, ohne andere Dinge zu ändern (wie stdin Manipulation etc.), und fängt es am äußeren Programm.

BTW, da ich code.InteractiveConsole nicht erben muss, sollte ich stattdessen code.interact(...) verwenden.