在单独的线程中运行SimpleXMLRPCServer并关闭 [英] Running SimpleXMLRPCServer in separate thread and shutting down

查看:339
本文介绍了在单独的线程中运行SimpleXMLRPCServer并关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要通过python中的SimpleXMLRPCServer测试的类.设置单元测试的方式是创建一个新线程,然后在其中启动SimpleXMLRPCServer.然后我运行所有测试,最后关闭.

I have a class that I wish to test via SimpleXMLRPCServer in python. The way I have my unit test set up is that I create a new thread, and start SimpleXMLRPCServer in that. Then I run all the test, and finally shut down.

这是我的ServerThread:

This is my ServerThread:

class ServerThread(Thread):
    running = True
    def run(self):
        self.server = #Creates and starts SimpleXMLRPCServer

        while (self.running):
            self.server.handle_request()

    def stop(self):
        self.running = False
        self.server.server_close()

问题是,如果它已经在handle_request中等待请求,则调用ServerThread.stop(),后跟Thread.stop()和Thread.join()不会导致线程正常停止.而且由于这里似乎没有任何中断或超时机制可以使用,因此我无所适从地干净地关闭服务器线程.

The problem is, that calling ServerThread.stop(), followed by Thread.stop() and Thread.join() will not cause the thread to stop properly if it's already waiting for a request in handle_request. And since there doesn't seem to be any interrupt or timeout mechanisms here that I can use, I am at a loss for how I can cleanly shut down the server thread.

推荐答案

两个建议.

建议之一是使用单独的进程而不是单独的线程.

Suggestion One is to use a separate process instead of a separate thread.

  • 创建独立的XMLRPC服务器程序.

  • Create a stand-alone XMLRPC server program.

subprocess.Popen()开始.

完成测试后将其杀死.在标准操作系统(非Windows)中,kill效果很好.但是,在Windows中,没有简单的终止功能,但是有一些解决方法.

Kill it when the test is done. In standard OS's (not Windows) the kill works nicely. In Windows, however, there's no trivial kill function, but there are recipes for this.

另一个建议是在XMLRPC服务器中具有一个导致服务器自毁的功能.您定义一个调用sys.exit()os.abort()的函数,或者引发一个类似的异常,该异常将停止该过程.

The other suggestion is to have a function in your XMLRPC server which causes server self-destruction. You define a function that calls sys.exit() or os.abort() or raises a similar exception that will stop the process.

这篇关于在单独的线程中运行SimpleXMLRPCServer并关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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