我尝试将一个方法称为线程,然后在StartServer方法正在后台运行时调用另一个方法,但是当执行self.Thread.run()时,代码将卡住。有任何想法吗 ?我尝试将启动服务器放在另一个类的外部函数中,但仍然存在该问题。
import time
import webview
import threading
from flask import Flask
class Windows:
def __init__(self, EntryPoint = "index.html"):
self.EntryPointContent = self.ReadPage(EntryPoint)
self.Thread = threading.Thread(target = self.StartServer)
self.Thread.daemon = True
self.Thread.run()
self.ShowWindows()
def StartServer(self):
app = Flask(__name__)
app.debug = False
app.reloader = False
@app.route("/")
def root():
return self.EntryPointContent
app.run()
def ReadPage(self, FileName):
File = open(FileName, "r")
return File.read()
def ShowWindows(self):
webview.create_window("Hey !", "http://localhost:5000")
webview.start()
app = Windows(EntryPoint="page.html")
答案 0 :(得分:1)
我猜是这样
app.reloader = False
没有按照您的期望去做。相反,尝试
app.run(use_reloader=False)
答案 1 :(得分:1)
致电Thread.run()
而不是Thread.start()
。运行将只在当前线程上调用您的StartServer
方法。下面是一个简短的示例,您可以尝试一下。
import threading
from time import sleep
def l(msg):
while True:
print(msg)
sleep(1)
thread = threading.Thread(target=lambda: l('foo'))
thread.start() # swap with thread.run()
l('bar')