def checkContent(self, content_): _content = content_ _lines = _content.split("\n") _count = 0 for _line in _lines: _count += 1 _oneLineReturnReg = re.search(r';[ \t]*return ', _line) if _oneLineReturnReg: self.raiseError( pyUtils.getCurrentRunningFunctionName(), "有一行内多个逻辑,其中有return的情况发生 : " + _oneLineReturnReg.group(0) ) _returnNotAtStart = re.search(r'^(.*[^ ^\t]) return ', _line) if _returnNotAtStart: _prefix = _returnNotAtStart.group(1) if re.search(r'case .*:', _prefix): self.raiseError( pyUtils.getCurrentRunningFunctionName(), "return 并不是新行起始 case : " + _returnNotAtStart.group(0) ) elif not _prefix.endswith("yield"): if not (_prefix.find('\'') > 0 or _prefix.find('"') > 0): self.raiseError( pyUtils.getCurrentRunningFunctionName(), "return 并不是新行起始 : " + _returnNotAtStart.group(0) )
def dataPathValidation(self, dataPath_: str): if dataPath_.find("..") >= 0: self.raiseError(pyUtils.getCurrentRunningFunctionName(), "数据路径不能包含..") return False elif dataPath_.find("\n") >= 0 or dataPath_.find("\r") >= 0: self.raiseError(pyUtils.getCurrentRunningFunctionName(), "数据路径不能包含 换行") return False return True
def runExcel(self, excelPath_: str, pwd_: str, cmdDict_: dict = {}, sheetName_: str = None): # cmdUtils.removeMacXattr(excelPath_)# 修改 excel 权限 # sys.exit(1) # Excel 依旧权限不够,强制重新开启 Finder。 cmdLogUtils.log("\n1.解析Excel : " + excelPath_ + "\n") _currentWorkBook = WorkBook() _currentWorkBook.initWithWorkBook(excelPath_) # 是否执行过 _isExecute = False # 循环Sheet页 for _sheetName in _currentWorkBook.sheetDict: if sheetName_: # 有指定Sheet if not _sheetName == sheetName_: # 不是指定的Sheet continue # 找下一个 _isExecute = True # 执行 _sheet = _currentWorkBook.sheetDict[_sheetName] if _sheet.sheetType != SheetType.CMD: self.info.raiseERR(pyUtils.getCurrentRunningFunctionName() + "\n" + "ExcelApp -> runExcel : " + _sheetName + " 不是 CMD 类型") print(" " * 4 + str(_sheetName) + " 配置解析中...") _sheetJsonDict = _sheet.toJsonDict() print(" " * 4 + str(_sheetName) + " 配置解析成功!") if ("dGlobalDict" in _sheetJsonDict) and ("lProcessSteps" in _sheetJsonDict): _globalDict = _sheetJsonDict["dGlobalDict"] # 全局参数 _cmdInfoDict = { "__folder__": os.path.dirname(excelPath_), "__pwd__": pwd_, "__time__": timeUtils.nowTimeStamp() } for _key in _globalDict: _value = _globalDict[_key] # 遍历参数,获取值 _globalDict[_key] = strUtils.replaceKeyToValueInTemplate( _cmdInfoDict, _value) # 将运行环境替换到全局变量中 jsonUtils.mergeAToB(cmdDict_, _globalDict) # 命令行覆盖掉参数 self.runServiceByJsonDict(_sheetJsonDict) break # 只执行出现的第一个WORKFLOW页 else: self.info.raiseERR(pyUtils.getCurrentRunningFunctionName() + "\n" + "ExcelApp -> runExcel : " + _sheetName + " 参数配置必须包含 dGlobalDict lProcessSteps") if sheetName_ and not _isExecute: print("待执行功能 : " + sheetName_ + " 不存在于当前Excel中")
def create(self): if self._isDestory: self.raiseError(pyUtils.getCurrentRunningFunctionName(), "is already destory ~ !") if self._isCreated: self.raiseError(pyUtils.getCurrentRunningFunctionName(), "is already _isCreated ~ !") self._isCreated = True # 累计 Base 的对象 self.app.baseCount = self.app.baseCount + 1 self.getRunningBaseObjectListBelongToThisClass().append(self)
def getSubClassObject(self, subClassName_: str): _subObject: BaseInService = self.sm.serviceProvider.getServiceSubObject(self, subClassName_) if _subObject: # 服务中创建的子对象,都必须继承自Base,便于统计管理 if not isinstance(_subObject, BaseInService): self.raiseError(pyUtils.getCurrentRunningFunctionName(), "subClassObject is not extends from BaseInService") # 服务中创建的子对象,不能是服务,免得复制粘贴代码导致的基类使用错误 if isinstance(_subObject, BaseService): self.raiseError(pyUtils.getCurrentRunningFunctionName(), "subClassObject is BaseService") _subObject.create() return _subObject else: return None
def doExcelFunc(self, sFunctionName_: str, dParameters_: dict): if hasattr(self, sFunctionName_): # 使用反射 _function = getattr(self, sFunctionName_) _function(dParameters_) else: self.raiseError(pyUtils.getCurrentRunningFunctionName(), " excel 不存在这个方法 : " + sFunctionName_)
def checkDeleteFolder(self, deleteFolderPath_: str): # 判断是否正在删除根目录。。。 if deleteFolderPath_.index(os.sep) < 0: self.raiseError(pyUtils.getCurrentRunningFunctionName(), deleteFolderPath_ + " : 注意!你要删除哪里?") sys.exit(1) else: _deleteSplitLength = len(deleteFolderPath_.split(os.sep)) - 2 if _deleteSplitLength <= 5: # 一般本机的目录结构。为了不错误的删除了内容,进行了一次强制长度判断。太短的路径,不会进行删除 # /盘符/子盘目录/自定义分类/ -- 移动硬盘的情况 # /Users/用户/分类(Download、desktop)/自定义分类/ -- 本机目录的情况 <以这个为安全层级数,防止误删除> self.raiseError( pyUtils.getCurrentRunningFunctionName(), " : 路径有点儿短,防错误路径,不予执行。。。 : \n " + deleteFolderPath_) sys.exit(1)
def test_flatMap(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + "------------------") _lines = self.sc.parallelize(["hello world", "hi"]) # flatMap 得到了一个由各列表中的元素组成的 RDD, 而不是一个由列表组成的 RDD _words = _lines.flatMap(lambda line: line.split(" ")).collect() for _word in _words: print("%s " % _word) # 读取json文件,返回一个二元组(文件路径,文件内容) _jsonRDD = self.sc.wholeTextFiles(self.testJsonFilePath) # 读取每一行json信息,将二元组的第二项,作为字符串解析成Json对象,将其中的 activityInfo 作为新 RDD 的元素。 def _getActivityInfoFunc(jsonInfoKV_): _jsonValue = jsonInfoKV_[1] _activityInfoDict = json.loads(_jsonValue)["activityInfo"] return _activityInfoDict _json_activityInfo_RDD = _jsonRDD.flatMap( lambda _jsonInfoKV: (_getActivityInfoFunc(_jsonInfoKV))) # 去重 _json_activityInfo_RDD.distinct() # RDD 转 DF _json_activityInfo_DF = self.spark.createDataFrame( _json_activityInfo_RDD) # 创建临时表 _json_activityInfo_DF.registerTempTable("activityInfo") _resultsRDD = self.sqlCtx.sql( "SELECT startTime.low,endTime.low FROM activityInfo WHERE id = 300001L" ) for _result in _resultsRDD.collect(): print("_result = " + str(_result))
def dataChanged(self): _arr: list = [] _firstValue: str = self.getRealValue(self.firstValue) _arr.append(_firstValue) _arr.append(self.compareType) _length: int = len(self.secondArr) for _idx in range(_length): _arr.append(self.getRealValue(self.secondArr[_idx])) # 获取比较结果 1-成功,0-失败,-1-无解 _compare_result: int = self.dataCompare(_arr) if _compare_result == -1: self.printResult(-1) self.raiseError(pyUtils.getCurrentRunningFunctionName(), "比较数据无解") return False, None if self.displayObject: if _compare_result == 0: # 不显示 return True, False else: # 显示 return True, True else: if _compare_result == 0: return True, False elif _compare_result == 1: return True, True
def test_createSchema(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + "------------------") # 数据 _jsonDatas = [{ 'a': 'aaa', 'b': 'bbb', 'c': 'ccc' }, { 'a': 'aaaa', 'b': 'bbbb', 'c': 'cccc', 'd': 'dddd', 'e': 'eeee' }] _jsonDatas = [json.dumps(_jsonDict) for _jsonDict in _jsonDatas] # 已知结构 schema = ['a', 'b', 'c', 'd'] fields = [ StructField(_fieldName, StringType(), True) for _fieldName in schema ] schema = StructType(fields) rdd = self.sc.parallelize(_jsonDatas) # 已知 结构 会被保留,未知结构会被抛弃 df = self.sqlCtx.read.schema(schema).json(rdd) for data in df.collect(): print("data = " + str(data)) df.registerTempTable("tempTable") _resultsRDD = self.sqlCtx.sql("SELECT c,d FROM tempTable") for _result in _resultsRDD.collect(): print("_result = " + str(_result))
def sample_array_operate_slice(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + " ------------------ -") # x[start:stop:step] # 一维数组 x = np.arange(10) print('x[:5] = ' + str(x[:5])) # 前五个元素 print('x[5:] = ' + str(x[5:])) # 索引五之后的元素 print('x[4:7] = ' + str(x[4:7])) # 中间的子数组 print('x[::2] = ' + str(x[::2])) # 每隔一个元素 print('x[1::2] = ' + str(x[1::2])) # 每隔一个元素,从索引1开始 # 当步长为负数的时候,可以理解成 start 参数和 stop 参数默认是被交换的 print('x[::-1] = ' + str(x[::-1])) # 所有元素,逆序的 print('x[5::-2] = ' + str(x[5::-2])) # 从索引5开始每隔一个元素逆序 # 多维子数组 np.random.seed(0) x2 = np.random.randint(10, size=(3, 4)) print('x2 = \n' + str(x2)) print('x2[:2, :3] = \n' + str(x2[:2, :3])) # 两行,三列 print('x2[:3, ::2] = \n' + str(x2[:3, ::2])) # 所有行,每隔一列 print('x2[::-1, ::-1] = \n' + str(x2[::-1, ::-1])) # 子数组维度也可以同时被逆序 # 获取数组的行和列 print('x2[:, 0] = ' + str(x2[:, 0])) # 获取 第一 列 print('x2[0, :] = ' + str(x2[0, :])) # 获取 第一 行 等价于 x2[0] # 抽取的是子视图,而不是副本,所以,修改这个子视图,就是在修改这个数组 x2_sub = x2[:2, :2] print('x2_sub = \n' + str(x2_sub)) # 前两行,前两列 的视图 # 要创建数组的副本,使用copy()方法 x2_sub_copy = x2_sub.copy() print('x2_sub_copy = \n' + str(x2_sub_copy)) # 两个数组是否值一致 if x2_sub.all() == x2_sub_copy.all(): print("x2_sub and x2_sub_copy value are all the same") # 两个对象的地址不一致 if not id(x2_sub) == id(x2_sub_copy): print("x2_sub and x2_sub_copy are not the same one")
def analysePrefabComponentRelationShip(self): _prefabPathDict = folderUtils.getFilePathKeyValue(self._prefabFolder, [".prefab"]) for _, _prefabPath in _prefabPathDict.items(): _prefabFileName = fileUtils.justName(_prefabPath) # prefab 文件 对应 Component 的 列表 self.prefabComponentDict[_prefabFileName] = [] # prefab 的 列表 _prefabList = fileUtils.dictFromJsonFile(_prefabPath) # prefab 内容 for _i in range(len(_prefabList)): # prefab 的 每一个 元素 _elementDict = _prefabList[_i] # 每一个 元素 的 类型 _elementType = _elementDict['__type__'] # 组件 和 加密字符串 的 对应字典。 if _elementType in self.componentEncryptClassDict.keys(): _componentJSName = self.componentEncryptClassDict[_elementType] # 转换成 js 脚本名 self.prefabComponentDict[_prefabFileName].append(_componentJSName) # 获取 Prefab 上的 js Component 脚本 _keyList = [] for _key, _list in self.prefabComponentDict.items(): if len(_list) == 0: _keyList.append(_key) for _key in _keyList: del self.prefabComponentDict[_key] for _key, _list in self.prefabComponentDict.items(): if _key != _list[0]: self.raiseError(pyUtils.getCurrentRunningFunctionName(), " 界面名 和 component 名称 不一致 " + _key + " : " + _list[0])
def destroy(self): if not self._isCreated: self.raiseError(pyUtils.getCurrentRunningFunctionName(), "is not create ~ !") self._isDestory = True # 清除累计 self.app.baseCount = self.app.baseCount - 1 self.app.runtimeObjectInfoDict[self.fullClassPath].remove(self)
def convertLayerName(self, layerName_: str): _layerName = layerName_ if _layerName.find(' ') > 0 or _layerName.find( '"') > 0 or _layerName.find('\'') > 0 or _layerName.find( '.') > 0 or _layerName.find('/') > 0: self.raiseError(pyUtils.getCurrentRunningFunctionName(), "层名错误 : " + _layerName) return _layerName
def sample_relation_with_python(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + " ------------------ -") pyList = [3.14, 2, 3, 4] npArray = np.array(pyList, dtype='float32') print('npArray = ' + str(npArray)) npArray2 = np.array([range(i, i + 3) for i in [2, 4, 6]]) print('npArray2 = \n' + str(npArray2))
def sample_arr_transpose(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + " ------------------ -") _rowCount = 4 _colCount = 3 _indexArr = np.arange(0, _rowCount * _colCount).reshape(_rowCount, _colCount) print('_indexArr = \n' + str(_indexArr)) print('_indexArr.T = \n' + str(_indexArr.T)) print('np.dot(_indexArr,_indexArr.T) = \n' + str(np.dot(_indexArr, _indexArr.T)))
def test_sparkStreaming(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + "------------------") self.getSubClassObject("SparkStreaming") self.getSubClassObject("Kafka") # self.showCurrentBaseObejctsInfo() self.sparkStreaming.destroy() self.kafka.destroy()
def test_jsonStrToDataFrame(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + "------------------") _jsonDataFrame = self.spark.read.json(self.testJsonFilePath) _jsonDataFrame.printSchema() _jsonDataFrame.show() _activityInfo = _jsonDataFrame.selectExpr("activityInfo") _activityInfo.show()
def isNaN(dataCompareObject_: DataCompare, valueC1_: str, valueC2_: str, valueC3_: str = None): if ( strUtils.is_number(valueC1_) and strUtils.is_number(valueC2_) ): _valueArr = [float(valueC1_), float(valueC2_)] if valueC3_: if not strUtils.is_number(valueC3_): dataCompareObject_.raiseError(pyUtils.getCurrentRunningFunctionName(), "WARN : 进行比较的数值,非数字类型无法比较 " + _mode + " : " + valueC1_ + "," + valueC2_ + "," + valueC3_) return None else: _valueArr.append(float(valueC3_)) return _valueArr else: dataCompareObject_.raiseError(pyUtils.getCurrentRunningFunctionName(), "WARN : 进行比较的数值,非数字类型无法比较 " + _mode + " : " + valueC1_ + "," + valueC2_) return None
def test_map(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + "------------------") _numsRDD = self.sc.parallelize([1, 2, 3, 4]) # map() 接收一个函数, 把这个函数用于 RDD 中的每个元素, 将函数的返回结果作为结果 _squaredRDD = _numsRDD.map(lambda x: x * x) # 输出每一个元素,平方数 for _num in _squaredRDD.collect(): print("%i " % _num)
def getAllRelationTableInfo(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + "------------------") # 读取sql内容 _sqlStr = fileUtils.readFromFile(self.sqlFilePath) # print('_sqlStr = ' + str(_sqlStr)) # _sqlWithOutComment = codeUtils.removeComment("sql", _sqlStr) # print('_sqlWithOutComment = ' + str(_sqlWithOutComment)) # # 去掉注释切分Sql输出查看每一个SQL # _sqlList = _sqlWithOutComment.split(";") # for _i in range(len(_sqlList)): # print('_sqlList[_i] = \n' + str(_sqlList[_i])) # 获取表和表中索取字段 _whatFromWhereInfo = self.belongToService.getSelectWhatFromWhere( _sqlStr) # 获取要执行的Sql列表 _sqlList = self.belongToService.whatFromWhereToQuerySqlList( _whatFromWhereInfo) # 腾讯 链接信息 _txPrestoInfo = dict({ 'host': 'ip', 'port': 'port', 'catalog': 'hive', 'serverName': 'TengXun', 'schema': 'olap' }) # 执行的sql列表输出,链接 presto 来执行这些 Sql 语句 for _i in range(len(_sqlList)): _querySql = _sqlList[_i] _result, _errList = dataUtils_presto.executePrestoSQL( _txPrestoInfo, _querySql) if _errList: print(_querySql) self.raiseError(pyUtils.getCurrentRunningFunctionName(), str(_errList)) else: if len(_result) == 0: print(_querySql) self.raiseError(pyUtils.getCurrentRunningFunctionName(), 'WARNING : no data')
def convertToUnityUIJson(self, layerDict_: dict, unityGameObject_: dict): if not layerDict_["isVisible"]: return if not "layerList" in layerDict_: self.raiseError( pyUtils.getCurrentRunningFunctionName(), "不是层 : " + layerDict_["name"] + " - " + layerDict_["realName"] + " - " + str(layerDict_["isVisible"])) _currentIdx = 0 unityGameObject_["children"] = [] _layerDictList = layerDict_["layerList"] if _layerDictList: for _layerDict in _layerDictList: if not _layerDict["isVisible"]: continue _unityLayerGameObject = {} _unityLayerGameObject["name"] = _layerDict["name"] _unityLayerGameObject["realName"] = _layerDict["realName"] _unityLayerGameObject["x"] = _layerDict["offsetX"] _unityLayerGameObject["y"] = _layerDict["offsetY"] _unityLayerGameObject["opacity"] = _layerDict["opacity"] _unityLayerGameObject["bbox"] = {} _unityLayerGameObject["bbox"]["left"] = _layerDict["bbox"][ "left"] _unityLayerGameObject["bbox"]["top"] = _layerDict["bbox"][ "top"] _unityLayerGameObject["bbox"]["right"] = _layerDict["bbox"][ "right"] _unityLayerGameObject["bbox"]["bottom"] = _layerDict["bbox"][ "bottom"] # 不同类型 if str(_layerDict["name"]).startswith("pre_"): _unityLayerGameObject["type"] = "prefab" _subUIName = str( _layerDict["name"]).split("_")[1] # 切出子ui名称 self.analysePsdFile(_subUIName) elif str(_layerDict["name"]).startswith("pic_"): _unityLayerGameObject["type"] = "sprite" elif str(_layerDict["name"]).startswith("txt_"): _unityLayerGameObject["type"] = "text" _unityLayerGameObject["text"] = _layerDict["text"] _unityLayerGameObject["fontSize"] = _layerDict["fontSize"] else: _unityLayerGameObject["type"] = "gameObject" self.convertToUnityUIJson(_layerDict, _unityLayerGameObject) # 获取层级 _unityLayerGameObject["index"] = _currentIdx _currentIdx += 1 # 记录节点 unityGameObject_["children"].append(_unityLayerGameObject)
def IconResize(self, dParameters_): _sourceFolder = sysUtils.folderPathFixEnd(dParameters_["sourceFolder"]) _targetFolder = sysUtils.folderPathFixEnd(dParameters_["targetFolder"]) _sizeList = dParameters_["sizeList"] _targetType = dParameters_["type"] _sourcePicList = folderUtils.getFilterFilesInPath( _sourceFolder, [".jpg", ".png"]) _imList = [] # image信息列表 for _sourcePicPath in _sourcePicList: # 要放缩的Icon _im = Image.open(_sourcePicPath) # 加载内存,方便获取信息 _sizeCompareValue = _im.width / _im.height if _sizeCompareValue > 1.1 or _sizeCompareValue < 0.9: # 校验宽高比,差太多提示一下 self.raiseError(pyUtils.getCurrentRunningFunctionName(), _sourcePicPath + " 作为图标,宽高比相差有点儿大") _imList.append(_im) _imList.sort(key=lambda _im: _im.width, reverse=True) # 按照由大到小的顺序 _sizeList.sort(key=lambda _size: _size, reverse=True) # 由大到小 if _sizeList[0] > _imList[0].width: self.raiseError( pyUtils.getCurrentRunningFunctionName(), "索取大小的最大值(" + str(_sizeList[0]) + ")大于给与大小的最大值(" + str(_imList[0].width) + ")") # Image实例.thumbnail((宽, 高))会改变Image实例本身,所以,又大到小进行逐步变化。 # 由大到小的,将每一个小于自己尺寸的ICON生成一遍。小的会覆盖大的生成的ICON,最后达到想要的结果。 for _im in _imList: # 先比大的,后比小的,小于等于最接近的会最后成为目标图片 for _size in _sizeList: # 放缩的目标值 if _size <= _im.width: # 目标值小于当前图片的大小。就使用者张图 _targetIconPath = os.path.join( _targetFolder, 'Icon-' + str(_size) + _targetType) _im.thumbnail( (_size, _size) ) # target Image 在内存内存中大小会变小,下一个循环比他要小。所以,_sizeList必须是倒叙的 if _targetType == ".png": _im.save(_targetIconPath) elif _targetType == ".jpg": _im.save(_targetIconPath, quality=95, subsampling=0) else: self.raiseError( pyUtils.getCurrentRunningFunctionName(), _targetType + " 格式无效,目标格式,只能是.png和.jpg中的一种")
def getRunningBaseObjectListBelongToThisClass(self): _runtimeObjectInfoDict: dict = self.app.runtimeObjectInfoDict if not self.fullClassPath: self.raiseError(pyUtils.getCurrentRunningFunctionName(), "self.fullClassPath is None") _currentObjectList: List[Base] = None if self.fullClassPath in _runtimeObjectInfoDict: _currentObjectList = _runtimeObjectInfoDict[self.fullClassPath] else: _currentObjectList = [] _runtimeObjectInfoDict[self.fullClassPath] = _currentObjectList return _currentObjectList
def changeDataPath(self, dataPath_: str): _dataPath: str = dataPath_ if _dataPath.find("this.") == 0: if not self.displayObject: self.raiseError(pyUtils.getCurrentRunningFunctionName(), "DataBase " + _dataPath + " 为UI数据路径,没有绑定是哪个UI") return None else: # 通过自己绑定的显示对象,获取,显示对象所处的数据路径 _disPath = disUtils.getDisPath(self.displayObject) _dataPath = _disPath + "." + _dataPath.split("this.")[1] return _dataPath
def test_createPairRDD(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + "------------------") _lines = self.sc.parallelize( ["key1 value1", "key2 value2", "key2 value22", "key3 value3"]) # 转换成键值对儿 _pairs = _lines.map(lambda _item: (_item.split(" ")[0], _item.split(" ")[1])) # 值字符串长6以内的保留 _pairs = _pairs.filter(lambda _keyValue: len(_keyValue[1]) <= 6) # 输出满足条件的每一个键值 for (_key, _value) in _pairs.collect(): print(str(_key) + " = " + str(_value))
def onDataChange(self, dataPath_: str): _value = self.sm.dc.gv(dataPath_) if isinstance(_value, str): # print('dataPath_ : ' + dataPath_ + " : " + _value) if dataPath_ in self.dataEventDict: _dataBases: List[DataBase] = self.dataEventDict[dataPath_] if _dataBases and len(_dataBases) > 0: for _i in range(len(_dataBases)): _dataBases[_i].dataChanged() else: if isinstance(_value, list): self.raiseError(pyUtils.getCurrentRunningFunctionName(), "<" + str(dataPath_) + "> 转换过后不能可有数组")
def test_accumulator(self): print(self.className + " - " + pyUtils.getCurrentRunningFunctionName() + "------------------") def accumulatorFunc(): global blankLines blankLines += 1 for i in range(10): accumulatorFunc() global blankLines print("blankLines = " + str(blankLines))
def getClassListWithNameSpace(self, path_: str): _lines = fileUtils.linesFromFile(path_) _lineLength = len(_lines) _nameSpaceDictList = [] for _lineIdx in range(_lineLength): _line = _lines[_lineIdx] _nameSpaceStr = r'^\s*namespace\s+([a-zA-Z0-9_\.]+)\s+\{' _nameSpaceReg = re.search(_nameSpaceStr, _line) if _nameSpaceReg: _nameSpace = _nameSpaceReg.group(1) _nameSpaceDict = {} _nameSpaceDict["namespace"] = _nameSpace _nameSpaceDictList.append(_nameSpaceDict) # 从下一行开始找,找到第一个没有闭合的 },就是当前 { 对应的 _lineAndCharIdx = self.belongToService.curlyBraces.getCloseCurlyBraces( _lineIdx + 1, _lines) if not _lineAndCharIdx == None: _closeLine = _lines[_lineAndCharIdx[0]] if not _closeLine.strip() == "}": self.raiseError( pyUtils.getCurrentRunningFunctionName(), " <closed,but not }> : " + _closeLine) else: # 正确情况下记录 _classDictList = self.getClassList( _lines, _lineIdx, _lineAndCharIdx[0]) for _classDict in _classDictList: _nameSpaceDict[ _classDict["className"]] = _classDict del _classDict["className"] _lineIdx = _lineAndCharIdx[0] else: self.raiseError(pyUtils.getCurrentRunningFunctionName(), " : not close") else: if _line.find("namespace ") >= 0: print("namespace Warning : " + str(_line)) return _nameSpaceDictList
def adjustIfElseReturn(self, content_): _content = content_ _oneLineReg = r'^(.*)(if|else if)\s*\((.*)\)\s*return\s+(.*);$' matches = re.finditer(_oneLineReg, _content, re.MULTILINE) for matchNum, match in enumerate(matches, start=1): _prefix = match.group(1) if not _prefix.strip() == "": self.raiseError( pyUtils.getCurrentRunningFunctionName(), "if/else if 和 return 成行,前缀必须是空白 : " + match.group(0) ) _blank = _prefix _ifOrIfElse = match.group(2) _ifContent = match.group(3) _returnContent = match.group(4) _targetCode = _blank + _ifOrIfElse + "(" + _ifContent + "){" + "\n" _targetCode += _blank + " return " + _returnContent + ";" + "\n" _targetCode += _blank + "}" _content = _content.replace(match.group(0), _targetCode) _oneLineReg = r'^(.*)else\s*return\s+(.*);$' matches = re.finditer(_oneLineReg, _content, re.MULTILINE) for matchNum, match in enumerate(matches, start=1): _prefix = match.group(1) if not _prefix.strip() == "": # 不是 #else 这样的宏 if not _prefix.startswith("#"): self.raiseError( pyUtils.getCurrentRunningFunctionName(), "else 和 return 成行,前缀必须是空白 : " + match.group(0) ) else: _blank = _prefix _returnContent = match.group(2) _targetCode = _blank + "else{" + "\n" _targetCode += _blank + " return " + _returnContent + ";" + "\n" _targetCode += _blank + "}" _content = _content.replace(match.group(0), _targetCode)