Python守护进程不显示

2024-10-02 10:32:18 发布

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

我读了How do you create a daemon in Python?和{a2},并试图编写一个非常简单的守护程序:

import daemon
import time
with daemon.DaemonContext():
    while True:
        with open('a.txt', 'a') as f:
            f.write('Hi')
        time.sleep(2)

执行python script.py操作会立即返回到终端(这是预期的行为)。但是a.txt从来没有写过,我也没有收到任何错误消息。这个简单的daemon有什么问题?


Tags: inimport程序txtyoutruea2time
3条回答

哈卡拉的回答解决了这里描述的问题。在

另外两件事:

  • Sander's code(提到的here)比python-daemon好。它更可靠。仅举一个例子:尝试用python-daemon启动同一个守护进程两次:大错误。有了Sander的代码:一个很好的通知“Daemon already running。”

  • 对于那些想使用python-daemon的人来说:DaemonContext()只生成一个守护进程。DaemonRunner()生成一个daemon+控制工具,允许执行python script.py start或{}等操作。

daemon.DaemonContext()有选项working_directory,它有默认的错误值/,也就是说,你的程序可能没有在那里创建新文件的权限。在

有一点是错误的,那就是它没有办法告诉你它出了什么问题:-)

根据定义,守护进程与父进程和任何控制终端分离。因此,如果它有什么要说的-例如错误消息-它将需要在成为守护程序之前进行安排。在

来自the ^{} FAQ document

Why does the output stop after opening the daemon context?

The specified behaviour in PEP 3143_ includes the requirement to detach the process from the controlling terminal (to allow the process to continue to run as a daemon), and to close all file descriptors not known to be safe once detached (to ensure any files that continue to be used are under the control of the daemon process).

If you want the process to generate output via the system streams ‘sys.stdout’ and ‘sys.stderr’, set the ‘DaemonContext’'s ‘stdout’ and/or ‘stderr’ options to a file-like object (e.g. the ‘stream’ attribute of a ‘logging.Handler’ instance). If these objects have file descriptors, they will be preserved when the daemon context opens.

设置一个工作的通信通道,例如日志文件。使用files_preserve选项,确保打开的文件不会与其他文件一起关闭。然后记录任何错误。在

相关问题 更多 >

    热门问题