起初:我正在尝试编写用于控制Flask简单服务器的GUI,因此我可以将我的应用程序分发给noobs(使用PyInstaller)
我正在使用多处理来启动Flask,然后将其关闭,但将其关闭似乎是个问题。我编写了简单的cli-controller作为概念验证,但它甚至忽略了sys.exit()
代码:
from multiprocessing import Process
import sys
from myapp import app
def run():
app.run()
server = Process(target=run)
server.start()
while True:
x = raw_input("Input something:")
if x == "x":
server.terminate()
server.join(timeout=10)
print(server.exitcode)
print("end here")
break
print("All done!")
sys.exit(1)
但结果让我大吃一惊: (< Enter>表示我按下了输入)
user@localhost:~$ ./run.py
Input something: * Running on http://127.0.0.1:5000/
* Restarting with reloader
Input something:x
None
end here
All done!
user@localhost:~$ <Enter> Traceback (most recent call last):
File "./run.py", line 42, in <module>
x = raw_input("Input something:")
EOFError
并且Flask仍在运行......
server.join() after terminate() but Flask is running anyway
server=...
中的所有内容从break
包裹起来if __name__ == "__main__:"
,但没有结果我错过了什么?
答案 0 :(得分:1)
我仍然不明白,为什么以前的版本不起作用,但我找到了这个解决方案:
from Tkinter import *
from ttk import *
import multiprocessing
from myapp import app
def make_ui(server):
def terminate_server():
if server is not None and server.is_alive():
server.terminate()
main.destroy()
def toggle_server():
global server
if server.is_alive():
server.terminate()
server.join()
else:
if server.exitcode:
server = multiprocessing.Process(target=run_in_behind, name="server")
server.start()
main = Tk()
appname = Label(main, text="Sociometry v.0.0.1", anchor="center")
appname.grid(row=0, column=0, columnspan=2, pady=2)
main.mainloop()
def run_in_behind():
config = {
"HOST": "127.0.0.1"
}
app.config.from_object(config)
app.run()
if __name__ == "__main__":
server = multiprocessing.Process(target=run_in_behind, name="server")
make_ui(server)