python2.X参数处理和初始化日志

语言:python 2.X

 

    BaseConfig.py处理传参示例代码:

#-*- coding: UTF-8 -*- 
import getopt
import sys,os
import traceback
import utils

class BaseConfig(object):
    _instance = None  

    def __new__(cls, *args, **kwargs):  
        if not cls._instance:  
            cls._instance = super(BaseConfig, cls).__new__(  
                                cls, *args, **kwargs)  
        return cls._instance
    
    def __init__(self):
        pass
    
    def main(self):
        arg_list = ["username=", 
                         "ip=", 
                         "s="]
        for arg in sys.argv:
            if arg.startswith('--'):
                ky = arg.split('=')[0][2:]
                if '%s='%ky not in arg_list:
                    arg_list.append(ky+'=')
        opts,args = getopt.getopt(sys.argv[1:],"o:t:",arg_list)
        BaseConfig.optArgs = opts,args
        BaseConfig.ip = ''
        BaseConfig.username = ''
        BaseConfig.compare = ''
        BaseConfig.waittime = ''
        
        for opt,arg in opts:
            if opt == '--s':
                BaseConfig.serialNum = arg
                if BaseConfig.adbType == None or BaseConfig.adbType == "":
                    BaseConfig.adbType = self.getadbType(BaseConfig.serialNum)
            elif opt == '--ip':
                BaseConfig.ip = arg
            elif opt == '--username':
                BaseConfig.username = arg
            elif opt == '-o':
                BaseConfig.compare = arg
            elif opt == '-t':
                BaseConfig.waittime = arg

if __name__ == "__main__":
    ba = BaseConfig()
    ba.main()

 

    ChildCls.py复用BaseConfig.py处理参数,以及初始化日志示例代码:

#-*- coding: UTF-8 -*- 

import os
import sys
import getopt
import getpass
import logging
import traceback
import json
import httplib
import socket
import time

corepath = os.path.dirname(__file__)
scriptpath = os.path.dirname(corepath)
sys.path.append(scriptpath)

class ChildCls():
    def __init__(self,itemName=""):  
        self.argsObj = BaseConfig()
        try:
            self.argsObj.main()
        except Exception,e:
            print e
        self.ip = self.argsObj.ip
        self.username = self.argsObj.username
        self.waittime = self.argsObj.waittime

    def initLog(self, rootPath = None):
        log_start_time = time.strftime('%Y%m%d_%H%M%S')
        logfilename = str(log_start_time) + ".log"
        rootpath = "./"
        if rootPath:
            rootpath = rootPath + os.sep
        logpath = rootpath + "logs" + os.sep
        print logpath
        if not os.path.exists(logpath):
            os.makedirs(logpath)
        logfilename = logpath + logfilename
        print logfilename
        logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    filename=logfilename,
                    filemode='a')
        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        console.setFormatter(formatter)
        if len(logging.getLogger('').handlers)<2:
            logging.getLogger('').addHandler(console)

    def exection(self):
        print self.ip
        print self.username
        print self.waittime

def main():
    global result_msg
    current_path = os.getcwd()
    print "current_path: ", current_path

    try:
        master = ChildCls()
        py_root_path = os.path.split(os.path.realpath(__file__))[0]
        print "py_root_path: ", py_root_path
        master.initLog(py_root_path + os.sep)
        logging.info(" ----- Started ------ ")
        master.exection()
    except:
        print ""
        logging.error(traceback.format_exc()) 
        # return None
    finally:
        os.chdir(current_path)
        logging.info(" -------------- Finished ------------- \r\n" + result_msg + "\r\n")
        logging.shutdown()
            
if __name__ == "__main__":
    main()
    os._exit(0)

 

    传参示例:

python ChildCls.py --ip 123.33.1.4 --username test -t 1000 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值