【问题标题】:Python Daemon getting caughtPython 守护进程被抓
【发布时间】:2017-05-23 19:01:04
【问题描述】:

我正在编写一个脚本来读取系统日志,但在守护进程时遇到了问题。它被随机挂起,我一生都无法弄清楚为什么。代码如下:

守护进程

daemon_context = daemon.DaemonContext(files_preserve=[fh.stream])
with daemon_context:
    logger.debug("In Daemon")
    main()

主要

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler("./debug.log")
logger.addHandler(fh)
logger.debug("First")

def main():
    while True:
        from schema import parsed, engine, session
        logger.debug("Main Loop")
        logger.debug(args)

        if args.filename is None:
            logger.debug("In If")
            with open("/absolute/path/to/log.log") as f:
                readlines = f.readlines()
                logger.debug(readlines)
            content = [x.split() for x in readlines]
            logger.debug(content)
        else:
            logger.debug("In Else")
            with open(args.filename) as f:
                readlines = f.readlines()
                logger.debug(readlines)
            content = [x.split() for x in readlines]
            logger.debug(content)

        logger.debug("After Ifs")

        conn = engine.connect()
        logger.debug(conn)
        rows = session.query(parsed).count()

        for entry in range(rows, len(content)):
        # Code inside this for loop is unimportant to the problem at hand

记录

我正在记录所有内容,以找出错误被捕获的位置。

当我使用python3 test.py --filename access.log 运行它时,我得到:

First
In Daemon
Main Loop
Namespace(filename='access.log')
In Else

这就是整个日志。它只是停止。

但是如果我运行python3 test.py,没有文件名参数,那么我会得到这个日志:

First
In Daemon
Main Loop
Namespace(filename=None)
In If
[]
[]
After Ifs
<sqlalchemy.engine.base.Connection object at 0x7fe11c1da5f8>

然后它会无限重复,直到我停止任务。

我只是想不通它为什么会停止。如果有人可以帮助我,那就太好了。在我尝试使用有效的python-daemon 之前,我有一个不同形式的这个脚本。所以我知道底层逻辑应该是合理的。

【问题讨论】:

  • open(args.filename) 中的异常如何处理?

标签: python logging daemon python-daemon


【解决方案1】:

这个

daemon_context = daemon.DaemonContext(files_preserve=[fh.stream])
with daemon_context:

不一样

with daemon.DaemonContext(files_preserve=[fh.stream]) as daemon_context:

我也不确定作为全局变量的记录器是否会在守护进程期间主进程死亡后幸存下来。你试过在main()里面初始化它吗?

【讨论】:

  • 如果我正确理解上下文管理器,两者之间的唯一区别是with 块中的“daemon_context”变量的值。但在这种情况下,它没有被使用。
猜你喜欢
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 2011-10-21
  • 2017-02-18
  • 1970-01-01
相关资源
最近更新 更多