【发布时间】:2017-12-05 21:30:56
【问题描述】:
我有以下脚本,它只是启动一个为动态创建的网站提供服务的网络服务器。为了获取动态数据,脚本会打开一个文件来读取数据。
我关心的是如何捕获 CTRL-C 命令来杀死 python 脚本,这样我就可以在脚本线程被杀死之前关闭文件。
我尝试了以下几件事,但都没有成功:
from flask import Flask, render_template
import time
# Initialize the Flask application
app = Flask(__name__)
fileNames = {}
fileDesc = {}
for idx in range(1,4):
fileNames["name{}".format(idx)] = "./name" + str(idx) + ".txt"
fileDesc["name{}".format(idx)] = open(fileNames["name{}".format(idx)],'r')
try:
@app.route('/')
def index():
# code for reading data from files
return render_template('index.html', var1 = var1)
@app.errorhandler(Exception)
def all_exception_handler(error):
print("Closing")
for key, value in fileDesc:
val.close()
print("Files closed")
if __name__ == '__main__':
app.run(
host="192.168.0.166",
port=int("8080"),
debug=True
)
except KeyboardInterrupt:
print("Closing")
for key, value in fileDesc:
val.close()
print("Files closed")
提前致谢。
【问题讨论】:
-
KeyboardInterrupts 在 python2 中不能按预期工作。你在什么蟒蛇上? -
您也可以尝试使用信号。阅读this
-
@cᴏʟᴅsᴘᴇᴇᴅ 我正在使用 Python3。
-
奇数。它应该工作。您可以尝试@idjaw 提到的信号处理程序。
-
@idjaw 我会检查你的链接。但是在本地应用程序的python中,它非常简单,我已经成功了,但是使用Flask就更复杂了。不知道是因为它停止线程还是什么。但我也会检查信号处理程序
标签: python exception flask try-catch copy-paste