【发布时间】:2014-03-10 15:50:05
【问题描述】:
关于在类之间共享“功能”的问题。
情况:
- 我自己的所有代码都在一个文件中
- 我正在使用 python-daemon 来守护我的脚本
- 使用类(Doorcamdaemon)来启动和运行。
- 它导入另一个具有循环功能的类(Doorcam)
- 我将sample script 用于守护程序功能,它展示了如何使用日志记录模块。
日志记录在脚本的主要部分和 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 类中也能工作?
【问题讨论】:
-
Thnx,已更正。简化示例代码时有错别字
-
请在您的问题中提供更多信息 - 您所说的不起作用是什么意思?错误(提供追溯)?意外输出(提供输入以及预期和实际输出)?
-
不得不承认上面的例子工作得很好,但我的代码不是......但事实就是如此。我必须搜索我在原始(大到粘贴)代码中出错的地方。我会回来的……
标签: python class logging daemon