退出 code.InteractiveConsole().interact() 而不退出主程序

Exit code.InteractiveConsole().interact() without exiting main program

我有一个 Python 程序需要嵌入 Python 交互式控制台。

我目前正在使用 code 模块中的 InteractiveConsole

code.InteractiveConsole().interact()

但是,如果我在控制台输入 exit(),整个程序就会退出。

如何在不退出主程序的情况下退出交互式控制台?

感谢@PhillipMartin,我在阅读他的 link 后设法做到了: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

这让 exit 在控制台中仅引发 SystemExit,而无需更改其他内容(如操作标准输入等),并在外部程序中拦截它。

顺便说一句,因为我不需要继承 code.InteractiveConsole 我应该使用 code.interact(...) 来代替。