首页 > 解决方案 > 代码在“退出”或“退出”后仍然执行,Python,Spyder

问题描述

from os.path import join

string=" Congratulations, you are about to embark upon one of life’s "

path=r"C:\Users\Nord.Kind\Desktop"
file="test.txt"

quit() 

# This should not execute, but it does!!
with open(join(path,file),"w")as wfile:
    wfile.write(string)

wfile.close()

在上面的代码示例中,代码仍然执行写入文件命令,即使它在退出之后也是如此。

当我使用退出时会发生同样的行为。

我正在使用 Spyder 3.6

每次我使用退出或退出时内核都会重新启动。

有什么帮助吗?

标签: pythonexitspyder

解决方案


一种方法是使用sys.exit()代替quit()

import sys

...   # code that executes

sys.exit()

...   # this code won't execute

但是,正如@AranFey 在评论中指出的那样,如果您的代码尝试执行read未定义变量的最后部分,它将引发错误。


推荐阅读