要写一个可以使用的python程序还需要比如日志输出,读取配置文件,作为守护进程运行等

读取配置文件

使用自带的ConfigParser模块

import os
import ConfigParser

  

获取配置文件路径并进行读取

path = os.path.realpath(__file__)
path = os.path.dirname(path)
configPath = path + '/config.cfg'

config = ConfigParser.ConfigParser()
config.read(configPath)

  

使用方法

agentConfig = {}
agentConfig['MYSQLport'] = config.get('MySQL', 'port')

  

日志输出

使用自带的logging库

import logging
import logging.handlers

定义日志级别

loggingLevelMapping = {
    'debug': logging.DEBUG,
    'info': logging.INFO,
    'error': logging.ERROR,
    'warn': logging.WARN,
    'warning': logging.WARNING,
    'critical': logging.CRITICAL,
    'fatal': logging.FATAL,
}

customLogging = config.get('Logging', 'logging_level')
agentConfig['LOGGINGlevel'] = loggingLevelMapping[customLogging.lower()]

定义日志文件路径和格式

logFile = agentConfig['LOGGINGfile']
handler = logging.handlers.RotatingFileHandler(logFile, maxBytes=10485760, backupCount=10) # 10MB files
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

handler.setFormatter(formatter)

mainLogger = logging.getLogger('main')
mainLogger.setLevel(agentConfig['LOGGINGlevel'])
mainLogger.addHandler(handler)
使用方法

mainLogger.info(" Messages Done")
mainLogger.debug(" ACK Messages")

守护进程

使用第三方库Python daemonizer class

from daemon import Daemon

定义一个类继承守护进程并且有run()方法

class pantalaimon(Daemon):
    def run(self):
        # Do stuff

pidFile = agentConfig['DAEMONpid']
daemon = pantalaimon(pidFile)

对守护进程的各种操作

if 'start' == sys.argv[1]:
        daemon.start()

    elif 'stop' == sys.argv[1]:
        daemon.stop()

    elif 'restart' == sys.argv[1]:
        daemon.restart()

    elif 'foreground' == sys.argv[1]:
        daemon.run()

    elif 'status' == sys.argv[1]:
        try:
                pf = file(pidFile,'r')
                pid = int(pf.read().strip())
                pf.close()
        except IOError:
                pid = None
        except SystemExit:
                pid = None

        if pid:
                print 'is running as pid %s.' % pid
        else:
                print 'is not running.'

    else:
        print 'Unknown command'
        sys.exit(1)