关于在课堂之间分享'功能'的问题 情况:
日志记录适用于脚本的主要部分和Doorcamdaemon类,但不适用于Doorcam类。
class Doorcamdaemon():
def __init__(self):
#skipping some content, not related to this issue
self.Doorcam=Doorcam()
def run(self):
self.Doorcam.startListening() #looping function
class Doorcam
def __init__(self):
#skipping somecontent, not related to this issue
def startListening(self):
while True:
logger.info('Hello')
app = Doorcamdaemon()
logger = logging.getLogger("DoorcamLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.FileHandler("/var/log/doorcam.log")
handler.setFormatter(formatter)
logger.addHandler(handler)
daemon_runner = runner.DaemonRunner(app)
daemon_runner.daemon_context.files_preserve=[handler.stream]
daemon_runner.do_action()
返回的错误是:
$ ./Doorcam.py start
Traceback (most recent call last):
File "./Doorcam.py", line 211, in <module>
app = Doorcamdaemon()
File "./Doorcam.py", line 159, in __init__
self.doorcam=Doorcam()
File "./Doorcam.py", line 18, in __init__
logger.info('Doorcam started capturing')
NameError: global name 'logger' is not defined
所以我明显的问题是:我如何才能在Doorcam课程中使它成功?
答案 0 :(得分:0)
尝试移动线
app = Doorcamdaemon()
在创建和设置记录器的行之后到。追溯告诉你:
记录器,而Doorcam的构造函数试图使用它
Doorcamdaemon尝试在自己的构造函数中的第159行构建一个Doorcam
因此,如果尚未定义记录器,则无法创建Doorcamdaemon。
Doorcam.__init__
中遗漏的部分内容与此问题相关:)