Skip to content

Instantly share code, notes, and snippets.

@komasaru komasaru/test_daemon.py
Last active Feb 22, 2018

Embed
What would you like to do?
Python script to do a process as a daemon.
#!/usr/local/bin/python3.6
import datetime
import sys
import traceback
from daemon import DaemonContext
from os import path
from time import sleep
from lockfile.pidlockfile import PIDLockFile
class TestDaemon:
def __init__(self):
self.basename = path.splitext(path.basename(__file__))[0]
self.work_dir = path.dirname(path.abspath(__file__))
def exec(self):
try:
dc = DaemonContext(
working_directory = self.work_dir,
pidfile = PIDLockFile("/tmp/{}.pid".format(self.basename)),
stderr = open("{}.err".format(self.basename), "a+")
)
with dc:
self.__do_process()
except Exception as e:
raise
def __do_process(self):
try:
while True:
with open("{}.txt".format(self.basename), "a") as f:
f.write(datetime.datetime.now().isoformat() + "\n")
sleep(10)
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = TestDaemon()
obj.exec()
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.