SimpleXMLRPC_在单独的线程中运行SimpleXMLRPCServer并关闭

在Python中使用SimpleXMLRPCServer进行测试时,遇到线程无法正常停止的问题。当服务器在等待请求时,调用stop方法无法立即结束线程。文章提出了两种解决方案:一是使用单独进程代替线程,通过subprocess.Popen启动并杀死;二是添加一个XMLRPC服务器内的自我销毁函数,如调用sys.exit或os.abort来终止进程。这两种方法可以确保服务器线程的干净关闭。
摘要由CSDN通过智能技术生成

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.

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

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.

解决方案

Two suggestions.

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

Create a stand-alone XMLRPC server program.

Start it with subprocess.Popen().

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.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值