Last active
July 20, 2023 19:31
-
-
Save komasaru/c4c0ea54e886fb0b72fa47196f71d439 to your computer and use it in GitHub Desktop.
Python script to do a process as a daemon.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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