在SocketServer请求之间重用变量

2024-10-04 15:29:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在类内为方法创建临时变量。并更新方法内部的变量。我想在循环内重用self.last_l。但它不起作用。

这是我的代码:

import socket, mouseapi, mouseinput
from sys import stdout, exit
from decimal import Decimal
from math import fabs
from datetime import datetime
import time
import SocketServer

UDP_IP = "192.168.1.100"
UDP_PORT = 5005


class MyUDPHandler(SocketServer.BaseRequestHandler):
    def setup(self):
        self.before = 0
        self.noise = 1.5
        self.noise_f = 0.8
        self.last_l = 0 # i want this temporary and updated on handle()

    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]
        start = time.clock()
        ndata = data.replace("[","")
        ndata = data.replace("]","")
        ndata = ndata.split(", ")        
        try:
            ndata[1] = ("%.2f" % float(ndata[1]))
            atas = ndata[1]
            atas_bawah = int(int(float(atas)*100))
            selisih = fabs(float(atas)-float(self.last_l)) # used here
            if selisih > self.noise_f:
                print "Selisih -> %.2f" % float(selisih)
                print "Sensor -> %.2f" % float(atas)
                self.last_l = atas # and updated here
                atas_bawah = int(int(float(atas)*100))
                end = time.clock()
                print "Latency -> %.2gs" % (end-start)
            if self.last_l == 0:
                self.last_l = atas # or updated here
        except keyboardInterrupt:
            sys.exit(1)

if __name__ == "__main__":
    HOST, PORT = UDP_IP, UDP_PORT
    server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
    server.serve_forever()

所以我希望打印的selish值小于或大于1。但它给我的不止一个。

^{pr2}$

我试着用全球范围来做最后一个。还是不行。

当我试图把global last_l放在last_l = 0的任何地方,并将self.last_l改为last_lhandle方法内。


Tags: 方法fromimportselftimeportfloatint
1条回答
网友
1楼 · 发布于 2024-10-04 15:29:04

处理程序无法看到对self.last_l的更新,因为在每个接受的请求上都会创建MyUDPHandler的新实例。一、 处理程序的实例不被重用。在

BaseRequestHandlerdocstring:

This class is instantiated for each request to be handled. The constructor sets the instance variables request, client_address and server, and then calls the handle() method.

可能的解决方案:

  • last_l值保留在全局范围内。在
  • last_l设置为self.server(本例中是UDPServer的实例)
  • 将带有__call__(request, client_address, server)方法的实例传递给SocketServer.UDPServer和管理器last_l状态。在

请注意,这些解决方案都不是线程安全的(即,只能在单线程服务器上可靠地工作)。对于线程安全的解决方案,您必须用锁来保护对全局变量的写入。在

第一个解决方案的例子(最简单的一个)。为清晰起见,跳过无关行:

...
last_l = 0

class MyUDPHandler(SocketServer.BaseRequestHandler):
    ...
    def handle(self):
        global last_l
        ...
        selisih = fabs(float(atas)-float(last_l)) # used here
        if selisih > self.noise_f:
            ...
            last_l = atas # and updated here
            ...
        if last_l == 0:
            last_l = atas # or updated here
 ...

相关问题 更多 >

    热门问题