2016-04-26 71 views
0

我有一个Python程序,需要嵌入Python交互式控制台。退出code.InteractiveConsole()。交互()不退出主程序

我目前使用InteractiveConsolecode模块:

code.InteractiveConsole().interact()

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

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

+0

你可能想看看这个。 https://www.reddit.com/r/Python/comments/30i599/gracefully_break_out_of_codeinteractiveconsole/ –

+0

@PhillipMartin非常感谢! –

回答

1

感谢@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只,在不改变其他的东西(如操纵标准输入等),并且拦截它在外部程序。

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