Pythonの簡単なスクリプトのフォーマット

Pythonで簡単なスクリプトを書くときに使えそうなフォーマットを書いたのでメモしておく。

#!/usr/bin/env python
# coding: utf-8
'''
This script is sample format script.
'''
 
import os
import sys
import logging
from optparse import OptionParser
# for Python 3.x
# from configparser import SafeConfigParser
from ConfigParser import SafeConfigParser
 
CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
CONFIG_FILE = os.path.join(CURRENT_DIR, 'script.conf')
LOG_FILE = os.path.join(CURRENT_DIR, 'script.log')
 
# Logging Setting
LOG_FORMAT = '%(asctime)s %(module)s %(levelname)s %(message)s'
logging.basicConfig(filename=LOG_FILE, level=logging.INFO, format=LOG_FORMAT)
 
# Option Setting
parser = OptionParser()
parser.add_option('-c', '--config', dest='configfile',
    help='Load the config file.')
 
(options, args) = parser.parse_args()
 
# Main Process
def main():
    # Debug
    # import pdb; pdb.set_trace()
    if options.configfile is None:
        configf = CONFIG_FILE
    else:
        configf = options.configfile
 
    if not os.path.isfile(configf):
        logging.error('File not found!: {0}'.format(configf))
        sys.exit(101)
 
    config = SafeConfigParser()
    config.read(configf)
 
    print(config.get('section', 'key'))
 
if __name__ == '__main__':
    logging.info('Script START')
    main()
    logging.info('Normal END')