-
<PYTHON>[데몬작성]Flower in my dev/Python 2015. 4. 28. 10:43
http://pydjango.tistory.com/51 에서 퍼온 글입니다.
Python으로 Daemon을 만드는 예제 코드 입니다.
일단 해당 예제를 실행시키기 위해서 다운로드 받아야 하는 페키지가 있는데 아래와 같이 받으면 됩니다.
python easy_install python-daemon위의 패키지를 다운로드 하시면 준비는 끝입니다.
본격적으로 코드는 아래와 같습니다.
123456789101112131415161718192021222324252627282930313233343536373839404142# To kick off the script, run the following from the python directory:# PYTHONPATH=`pwd` python testdaemon.py start#standard python libsimport loggingimport time#third party libsfrom daemon import runnerclass App():def __init__(self):self.stdin_path = '/dev/null'self.stdout_path = '/dev/tty'self.stderr_path = '/dev/tty'self.pidfile_path = '/var/run/testdaemon/testdaemon.pid'self.pidfile_timeout = 5def run(self):while True:#Main code goes here ...#Note that logger level needs to be set to logging.DEBUG before this shows up in the logslogger.debug("Debug message")logger.info("Info message")logger.warn("Warning message")logger.error("Error message")time.sleep(10)app = App()logger = logging.getLogger("DaemonLog")logger.setLevel(logging.INFO)formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")handler = logging.FileHandler("/var/log/testdaemon/testdaemon.log")handler.setFormatter(formatter)logger.addHandler(handler)daemon_runner = runner.DaemonRunner(app)#This ensures that the logger file handle does not get closed during daemonizationdaemon_runner.daemon_context.files_preserve=[handler.stream]daemon_runner.do_action()cs 22 ~ 24번째 라인에 Daemon에서 실행시켜야 하는 부분을 넣으면 정상적으로 실행됩니다. 나머지 부분은 크게 어려울이 없을 것으로 예상되어 집니다.
로그 디렉토리(/var/log/testdaemon), PID 디렉토리(/var/run/testdaemon)은 만들어 놓으셔야 합니다.
아래는 Daemon을 inittab 부분에 넣는 부분입니다.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849#! /bin/bash# Copyright (c) 1996-2012 My Company.# All rights reserved.## Author: Bob Bobson, 2012## Please send feedback to bob@bob.com## /etc/init.d/testdaemon#### BEGIN INIT INFO# Provides: testdaemon# Required-Start:# Should-Start:# Required-Stop:# Should-Stop:# Default-Start: 3 5# Default-Stop: 0 1 2 6# Short-Description: Test daemon process# Description: Runs up the test daemon process### END INIT INFO# Activate the python virtual environment. /path_to_virtualenv/activatecase "$1" instart)echo "Starting server"# Start the daemonpython /usr/share/testdaemon/testdaemon.py start;;stop)echo "Stopping server"# Stop the daemonpython /usr/share/testdaemon/testdaemon.py stop;;restart)echo "Restarting server"python /usr/share/testdaemon/testdaemon.py restart;;*)# Refuse to do other stuffecho "Usage: /etc/init.d/testdaemon.sh {start|stop|restart}"exit 1;;esacexit 0cs 'Flower in my dev > Python' 카테고리의 다른 글
<PYTHON>[subprocess] (0) 2015.05.07 <PYTHON>[Unix Time] (0) 2015.04.29 <PYTHON>[BeautifulSoup] (0) 2015.04.27 <PYTHON>특정 날짜가 지나면 파일을 지우기 (0) 2015.04.27 <PYTHON>이더레이터?? 제너레이터?? (0) 2015.04.23