简体   繁体   中英

Cannot kill Python script in thread

I'm writing a beginner script in python with threads and Flask using IDLE.

When I exit with ctrl+c or click "stop" in IDLE, the script still continued to run in the background.

What is wrong in my code?

from flask import Flask, render_template
import datetime
import threading
import time
xa=0
def f1():
   i=1
   while(1):
      global xa
      xa=xa+1
      print(xa, "in f1")
      time.sleep(3)

t1=threading.Thread(target=f1)
t1.start()

app = Flask(name)
@app.route("/")
def hello():
   now = datetime.datetime.now()
   timeString = now.strftime("%Y-%m-%d %H:%M")
   templateData = {
      'title' : xa,
      'time': timeString
      }
   return render_template('index.html', **templateData)
if name == "main":
   app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)

i need run a app in background and do a job every time user want answer , see the answer in browser how can i do with thread and flask?

Try the following:

t1=threading.Thread(target=f1)
t1.daemon = True
t1.start()

If you don't make your thread a daemon thread, it will keep running, even when you kill the main thread, so your program won't quit when you try ctrl+c .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM