Created
May 4, 2014 09:50
-
-
Save dexbol/d7194f73322f6a42a9e6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import os | |
import subprocess | |
import logging | |
import argparse | |
''' Make a python script as daemon. | |
Usage: | |
python daemon.py start|stop|restart | |
You can use this for some scenes such as subversion hooks or init.d | |
''' | |
START_STOP_DAEMON = '/sbin/start-stop-daemon' | |
INTERPRETER = '/usr/bin/python' | |
SCRIPT = 'your-python-script-absolute-path' | |
PID_FILE = '/var/run/your-proejct.pid' | |
LOG_NAME = 'project-name' | |
LOG_FILE = '/var/log/yourproject.log' | |
LOG_DEBUG_FILE = '/var/log/yourproject-debug.log' | |
def getLogger(): | |
logger = logging.getLogger(LOG_NAME) | |
ih = logging.FileHandler(LOG_FILE) | |
dh = logging.FileHandler(LOG_DEBUG_FILE) | |
ih.setLevel(logging.INFO) | |
dh.setLevel(logging.DEBUG) | |
logger.addHandler(ih) | |
logger.addHandler(dh) | |
logger.setLevel(logging.DEBUG) | |
return logger | |
logger = getLogger() | |
def start_server(): | |
logger.debug('start..') | |
try: | |
subprocess.check_call([START_STOP_DAEMON, | |
'--start', | |
'--background', | |
'--pidfile', PID_FILE, | |
'--make-pidfile', | |
'--exec', INTERPRETER, | |
'--', SCRIPT]) | |
except subprocess.CalledProcessError as e: | |
logger.error('error code: ' + str(e.returncode)) | |
logger.error('error output: ' + str(e.output)) | |
def stop_server(): | |
logger.debug('stop..') | |
try: | |
subprocess.check_call([START_STOP_DAEMON, | |
'--stop', | |
'--pidfile', PID_FILE]) | |
os.remove(PID_FILE) | |
logger.debug('remove: ' + PID_FILE) | |
except subprocess.CalledProcessError as e: | |
logger.error('error code: ' + str(e.returncode)) | |
logger.error('error output: ' + str(e.output)) | |
def restart_server(): | |
stop_server() | |
start_server() | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('act', action='store') | |
action = vars(parser.parse_args())['act'] | |
if action == 'start': | |
start_server() | |
elif action == 'stop': | |
stop_server() | |
elif action == 'restart': | |
restart_server() | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment