如何解决内存问题,而 运行 代码永远

How to fix a memory problem while running a code forever

这是一个线程,我总是在其中检查许多占用传感器中的一个(或多个)是否 return 1(有人进入房间)以打开灯。但是,它全部写在 while True 循环中,我认为这对内存非常不利,因为我总是存储在一个变量中。注意 return_message() 函数总是 returning 一个值。那么如何解决这个问题呢?

def turning_lights_on():
    while True:
        for occupancy_sensor_ids in ids :
            # get the lights ids in the room according to the occupancy sensor id
            lights_id = db.light_devices(occupancy_sensor_ids)
            # the return value of the occupancy sensor is stored in message_occ_sensor
            # but a topic containing the id of the sensor must be used here, so need to be changed
            message_occ_sensor = occupancy_sensor.return_message(occupancy_sensor_ids)

            # loop to send commands to all the lights in the room
            for lights in lights_id:
                # the state of lights ON/OFF is returned
                # I considered that every topic starts by the device ID
                state_light_tunable = light_sub.return_message(lights +"/stat/POWER")

                if message_occ_sensor == "1" :
                    if state_light_tunable == "OFF":
                        # topics are to be modified and deviceID must be imported from mongoDB
                        #lights_id is imported from mongoDB
                        client.publish(lights +"/cmnd/POWER", 1)

仅仅因为某些东西处于 while True 循环中,并不意味着它一定会出现内存问题。

您在循环迭代之间没有保留任何数据,您的所有变量都会被覆盖,因此旧数据将没有引用,Python 垃圾收集器会为您删除它们.

不用担心!