RuntimeError: threads can only be started once Python Tkinter webserver

雨燕双飞 提交于 2021-01-28 06:48:45

问题


I am trying to create a webserver in python which can be started and stopped using a tkinter GUI. In tkinter I have a button which will call start() and a button that will call stop(). Initially everything works fine, the server starts when I click the button and it also stops when I click the stop button. When I try to restart the server again using the start button, I get a runtime error

RuntimeError: threads can only be started once

I believe it has something to do with the fact that I have already initialized threading in my init, and I can not figure out how to get this to work.

I have read through the threading docs multiple times, but I am struggling to understand it entirely. Any assistance would be greatly appreciated.

Thank you!

import threading
import socketserver
import http.server
import os


class WebServer(object):

    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.handler = http.server.SimpleHTTPRequestHandler
        self.server = socketserver.TCPServer((self.host, self.port), self.handler)
        socketserver.TCPServer.allow_reuse_address = True
        self.server_thread = threading.Thread(target=self.server.serve_forever, name="Server_Thread")
        self.server_thread.setDaemon(True)

    def start(self):
        web_dir = os.path.join(os.path.dirname(__file__), 'www')
        os.chdir(web_dir)
        self.server_thread.start()

    def stop(self):
        os.chdir('..')
        self.server.shutdown()
        self.server.server_close()

回答1:


As the python documentation states, the start method of the Thread object can only be called once.

In your case, you can create new instance of the Thread object in the start method:

def start(self):
    web_dir = os.path.join(os.path.dirname(__file__), 'www')
    os.chdir(web_dir)
    self.server_thread = threading.Thread(target=self.server.serve_forever, name="Server_Thread")
    self.server_thread.start()

In addition you also may clean the reference to the thread in stop method:

self.server_thread = None


来源:https://stackoverflow.com/questions/51582467/runtimeerror-threads-can-only-be-started-once-python-tkinter-webserver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!