语言: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