Skip to main content
 首页 » 编程设计

python之退出脚本后如何返回到 python shell

2025年05月04日15telwanggs

我的 python 脚本有几个 sys.exit() 调用可以在特定条件下终止。为了测试它,我打开了一个 python shell 并运行 exec(open('script.py').read())。每当我调用 sys.exit() 时,脚本就会终止,同时 python shell 也会终止,这很烦人。

因此,我尝试发挥创意,并尝试通过检查堆栈来确定我的脚本是从命令行运行还是从 shell 运行。来源:Detect if python script is run from an ipython shell, or run from the command line

def exit_now(exit_status): 
    os.system('pause') 
 
    if PythonShell:  # how do I return to the python shell ? 
        ??? 
    else:  # exit if we are running from the commandline 
        sys.exit(exit_status) 
 
... 
 
# check if this was run from inside a python shell 
frames = len(inspect.stack()) 
if frames > 1: 
    PythonShell = True 
else: 
    PythonShell = False 
 
... 
 
if condition1: 
    exit_now(1) 
 
if condition2: 
    exit_now(2) 
 
... 
 
exit_now(0) 

如何在终止脚本后返回到 python shell?

请您参考如下方法:

python -i <script>

'i' 用于交互。