函数中的对象不工作。把我的头撞到这个上面

2024-03-28 16:34:06 发布

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

我在一个模块中使用日志函数。它在函数“set”的外部工作正常,但在内部表示没有定义logger。救命啊?你知道吗

from peewee import *
import datetime
import logging
import json

#...

# Start up logging
logger = logging.getLogger(__name__)
logger.info("State library started...")

# ...

def set(module, device, state, attributes=None):
    """ Set the state of the specified device"""
    try:
        acquire_lock(device)
    except:
        #state object doesn't exist yet
        pass
    try:
        state_object = StateTable.select().where(StateTable.device == device).get()
    except:
        state_object = StateTable()

    state_object.device = device
    state_object.state = state
    state_object.attributes = attributes
    state_object.lastChange = datetime.datetime.now()
    state_object.save()
    logger.debug("Setting state for", device, "with state", state, "and attributes", attributes)
    release_lock(device)
    logger.debug("SETTING MQTT STATE")
    attributes_mqtt = {"device" : device, "module" : module, "state" : state, "attributes" : json.loads(attributes)}
    logger.debug("MQTT:", attributes_mqtt)
    mqttc.publish("state", json.dumps(attributes_mqtt))

我把它放在pastie上,因为SO不让我发布完整的代码。你知道吗

http://pastie.org/9125006


Tags: 函数debugimportjsondatetimeobjectdevicelogging
1条回答
网友
1楼 · 发布于 2024-03-28 16:34:06

您好,根据您在pastie上的代码,记录器是在函数集之外定义的(将其视为变量),因此要在函数中使用它,您必须将其传递给函数,即您的定义应该是这样的函数

def set(module, device, state, logger, attributes=None):
    """ Set the state of the specified device"""
    try:
            acquire_lock(device)
    except:
            #state object doesn't exist yet
            pass
    try:
            state_object = StateTable.select().where(StateTable.device == device).get()
    except:
            state_object = StateTable()

    state_object.device = device
    state_object.state = state
    state_object.attributes = attributes
    state_object.lastChange = datetime.datetime.now()
    state_object.save()
    logger.debug("Setting state for", device, "with state", state, "and attributes", attributes)
    release_lock(device)
    logger.debug("SETTING MQTT STATE")
    attributes_mqtt = {"device" : device, "module" : module, "state" : state, "attributes" : json.loads(attributes)}
    logger.debug("MQTT:", attributes_mqtt)
    mqttc.publish("state", json.dumps(attributes_mqtt))

然后调用set函数时,将记录器作为参数传递。你知道吗

相关问题 更多 >