간만에 좋은 코드 하나 올려 드립니다.

Python으로 Daemon을 만드는 예제 코드 입니다.

일단 해당 예제를 실행시키기 위해서 다운로드 받아야 하는 페키지가 있는데 아래와 같이 받으면 됩니다.

python easy_install python-daemon

위의 패키지를 다운로드 하시면 준비는 끝입니다. 

본격적으로 코드는 아래와 같습니다.


# To kick off the script, run the following from the python directory:
#   PYTHONPATH=`pwd` python testdaemon.py start

#standard python libs
import logging
import time

#third party libs
from daemon import runner

class 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 = 5
            
    def 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 logs
            logger.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 daemonization
daemon_runner.daemon_context.files_preserve=[handler.stream]
daemon_runner.do_action()

22 ~ 24번째 라인에 Daemon에서 실행시켜야 하는 부분을 넣으면 정상적으로 실행됩니다. 나머지 부분은 크게 어려울이 없을 것으로 예상되어 집니다.

로그 디렉토리(/var/log/testdaemon), PID 디렉토리(/var/run/testdaemon)은 만들어 놓으셔야 합니다. 

아래는 Daemon을 inittab 부분에 넣는 부분입니다.


#! /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/activate

case "$1" in
  start)
    echo "Starting server"
    # Start the daemon 
    python /usr/share/testdaemon/testdaemon.py start
    ;;
  stop)
    echo "Stopping server"
    # Stop the daemon
    python /usr/share/testdaemon/testdaemon.py stop
    ;;
  restart)
    echo "Restarting server"
    python /usr/share/testdaemon/testdaemon.py restart
    ;;
  *)
    # Refuse to do other stuff
    echo "Usage: /etc/init.d/testdaemon.sh {start|stop|restart}"
    exit 1
    ;;
esac

exit 0


import twitter
twitter_api=twitter.Twitter(domain="api.twitter.com", api_version='1')
WORLD_WOE_ID = 1
world_trends = twitter_api.trends._(WORLD_WOE_ID)
trends = [ trend for trend in world_trends()[0]['trends'] ]

파이썬을 이용하여 간단하게 사용할 수 있는 파일 서버 만들기 입니다.

전송하고자 하는 폴더에서 아래와 같은 명령어를 입력하도록 합니다.

   python -m SimpleHTTPSever 8000

이렇게 하시면 8000으로 웹서버가 열리게 되고 파일목록이 보이며 다운로드 받을 수 있도록 되어 있습니다.



'PYTHON > CODE' 카테고리의 다른 글

[CODE]Unique 리스트 값 찾기  (0) 2012.12.14
[CODE] 디렉토리 리스트 가져오기  (0) 2012.12.13
[CODE] 파이썬 윈도우 서비스 등록  (0) 2012.11.15
[CODE] 지금 시간 얻어오기  (0) 2012.11.15
[CODE] 오늘날짜 얻어오기  (0) 2012.11.14
class Person:
            def __init__(self):
                        self.name = None
                        self.gender = None
            def getName(self):
                        return self.name
            def getGender(self):
                        return self.gender
class Male(Person):
            def __init__(self, name):
                        print "Hello Mr." + name
class Female(Person):
            def __init__(self, name):
                        print "Hello Miss." + name
class Factory:
            def getPerson(self, name, gender):
                        if gender == 'M':
                                     return Male(name)
                        if gender == 'F':
                                     return Female(name)
if __name__ == '__main__':
            factory = Factory()
            factory.getPerson("chetan", "M")

 

'PYTHON > 강좌' 카테고리의 다른 글

Python Unittest  (1) 2017.02.06
01. Python 프로그램 로깅  (0) 2012.12.05
[PATTERN 2] Command 패턴  (0) 2012.11.19

+ Recent posts