功能内的对象不起作用。对着这一个摇头

时间:2014-04-29 09:45:16

标签: python scope

我在模块中使用日志记录功能。它在函数“set”的外部工作正常,但在其中表示没有定义记录器。帮助

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

我把它放在了贴纸上,因为我不会让我发布完整的代码。

http://pastie.org/9125006

1 个答案:

答案 0 :(得分:0)

嗨我根据你在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函数时,将logger作为参数传递。