运行时错误:线程只能启动一次 Python Tkinter 网络服务器 [英] RuntimeError: threads can only be started once Python Tkinter webserver

查看:49
本文介绍了运行时错误:线程只能启动一次 Python Tkinter 网络服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中创建一个可以使用 tkinter GUI 启动和停止的网络服务器.在 tkinter 中,我有一个调用 start() 的按钮和一个调用 stop() 的按钮.最初一切正常,当我单击按钮时服务器启动,当我单击停止按钮时它也会停止.当我尝试使用开始按钮再次重新启动服务器时,出现运行时错误

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

我相信这与我已经在 init 中初始化线程有关,但我不知道如何让它工作.

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.

谢谢!

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()

推荐答案

作为 python 文档 声明Thread对象的start方法只能调用一次.

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

在您的情况下,您可以在 start 方法中创建 Thread 对象的新实例:

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()

另外你也可以在stop方法中清除对线程的引用:

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

self.server_thread = None

这篇关于运行时错误:线程只能启动一次 Python Tkinter 网络服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆