我读了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
有什么问题?
哈卡拉的回答解决了这里描述的问题。在
另外两件事:
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 :
设置一个工作的通信通道,例如日志文件。使用
files_preserve
选项,确保打开的文件不会与其他文件一起关闭。然后记录任何错误。在相关问题 更多 >
编程相关推荐