Skip to main content
 首页 » 编程设计

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

2024年10月24日8mq0036

我有一个 Python 程序需要嵌入 Python Interactive Console。

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

code.InteractiveConsole().interact()

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

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

请您参考如下方法:

感谢@PhillipMartin,我在阅读他的链接后设法做到了: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,而无需更改其他内容(如操作 stdin 等),并在外部程序中拦截它。

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