def UnityWinProjToExe(): global WinAppName logFile = "%s/autobuild.txt" % GetUnityOrgOutPath() f = open(logFile, "w") f.close() projPath = GetUnityProjPath() #生成EXE cmd = "" if IsMacPlatform(): cmd = "/Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -nographics -projectPath %s -executeMethod %s -logFile " + logFile elif IsWindowsPlatform(): cmd = "Unity.exe -quit -batchmode -nographics -projectPath %s -executeMethod %s -logFile " + logFile else: print "不支持此平台打包" return False montior = tail.Tail(logFile) montior.register_callback(MonitorLine) cmd = cmd % (projPath, "AssetBundleBuild.Cmd_Win") print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在生成EXE...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) winExe = "%s/%s" % (GetWinExportProjPath(), WinAppName) if (not os.path.exists(winExe)) or (not os.path.isfile(winExe)): print "\n生成EXE失败~~!!!\n" return False return True
def UnityMacProjToApp(): global MacAppName logFile = "%s/autobuild.txt" % GetUnityOrgOutPath() f = open(logFile, "w") f.close() projPath = GetUnityProjPath() cmd = "" if IsMacPlatform(): cmd = "/Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -nographics -projectPath %s -executeMethod %s -logFile " + logFile elif IsWindowsPlatform(): cmd = "Unity.exe -quit -batchmode -nographics -projectPath %s -executeMethod %s -logFile " + logFile else: print "不支持此平台打包" return False montior = tail.Tail(logFile) montior.register_callback(MonitorLine) cmd = cmd % (projPath, "AssetBundleBuild.Cmd_Mac") print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在生成App...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) macApp = "%s/%s.app" % (GetMacExportProjPath(), MacAppName) #print macApp if (not os.access(macApp, os.F_OK)): print "\n生成App失败~~!!!\n" return False return True
def tail_follow(): me = threading.currentThread() me.logfile = '' while getattr(me, "aktiv", True): if logfile.get() != me.logfile: try: log.stop() except: pass try: me.logfile = logfile.get() if cfg.debug: print("[%s] registering logfile %s" % (me.name, me.logfile)) if cfg.parse: if cfg.debug: print("[%s_parse] start parsing whole file %s" % (me.name, me.logfile)) try: MMDVM.FullParse = True startat = time.time() with open(me.logfile) as file_: MMDVM.set('Parsing_File', me.logfile) me.filename = me.logfile for line in file_: line_parser(line, True) endat = time.time() except: if cfg.debug: print( "[%s_parse] error while parsing whole file %s" % (me.name, me.logfile)) raise print("Unexpected error:", sys.exc_info()[0]) duration = str(int((endat - startat) * 10) / 10) MMDVM.FullParse = False MMDVM.set('Parsing_Duration', duration) if cfg.debug: print( "[%s_parse] finished parsing whole file %s in %s seconds" % (me.name, me.logfile, duration)) log = tail.Tail(me.logfile, cfg.debug, me.name) log.register_callback(line_parser) log.follow() except: if cfg.debug: print("[%s] error while initialising tail %s" % (me.name, me.logfile)) raise else: #nothin do do here pass time.sleep(1) try: log.stop() except: pass
def __init__(self, initLength): self.length = initLength self.tails = [] self.dead = False for i in range(0, self.length): self.tails.insert(i, tail.Tail(3 * con.tileWidth, 3 * con.tileWidth))
def __init__(self, logFile, callback, threadId): self.logFile = logFile self.tail = tail.Tail(self.logFile) self.threadId = threadId print "\tTail: init ID #"+ str(self.threadId) self.tail.register_callback(callback) threading.Thread.__init__(self)
def UnityAndroidProjToApk(): logFile = "%s/autobuild.txt" % GetUnityOrgOutPath() f = open(logFile, "w") f.close() projPath = GetUnityProjPath() #生成APK cmd = "" if IsMacPlatform(): cmd = "/Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -nographics -projectPath %s -executeMethod %s -logFile " + logFile elif IsWindowsPlatform(): cmd = "Unity.exe -quit -batchmode -nographics -projectPath %s -executeMethod %s -logFile " + logFile else: print "不支持此平台打包" return False montior = tail.Tail(logFile) montior.register_callback(MonitorLine) cmd = cmd % (projPath, "AssetBundleBuild.Cmd_Apk") print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在生成APK...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) return True
def checkFood(self, grid): if (self.tails[0].x / self.tails[0].width == grid.currentFood[0] and self.tails[0].y / self.tails[0].width == grid.currentFood[1]): self.tails.insert( self.length, tail.Tail(self.tails[self.length - 1].x, self.tails[self.length - 1].y)) self.tails.insert( self.length + 1, tail.Tail(self.tails[self.length - 1].x, self.tails[self.length - 1].y)) self.tails.insert( self.length + 2, tail.Tail(self.tails[self.length - 1].x, self.tails[self.length - 1].y)) self.length += 3 grid.setFood(self)
def doSend(self): global condition try: # 使用tail插件完成`tail -f`的功能 t = tail.Tail('thefile.txt') # 注册回调,将消息广播给client客户端 t.register_callback(broadcastMessage) t.follow(s=2) except Exception as TailError: print 'error'
def _tail_thread(self, tail_file): print "wait for tail file ... %s" % tail_file while True: if os.path.exists(tail_file): print "Start tail file..... %s" % tail_file break t = tail.Tail(tail_file) t.register_callback(self._unity_log_tail) t.follow(s=0.1)
def __init__(self, name=None, conf=None): multiprocessing.Process.__init__(self,name = name) ZBase.__init__(self,'TailProcess_%s' % name) self.name = name self.conf = conf self.tailer = tail.Tail(self.conf['log_path'], self.conf['max_size']) self.data = {} self.analyseResult = zplugin.DICT self.regular = {} self.transform = {} self.initRegular()
def start_thread_to_tail(tail_file): """ start a thread to tail a file :param tail_file: :return: """ print 'Wait for tail file... {}'.format(tail_file) while True: if os.path.exists(tail_file): print 'Start tail file... {}'.format(tail_file) break t = tail.Tail(tail_file) t.register_callback(log_tail) t.follow(s=1)
def BuildObbFrom(fileDir, outDir, apkName, patchName, apkVersion): logFile = os.path.dirname(os.path.realpath(__file__)) + "/jobb.txt"; # 如果文件不存在则重新生成 f = open(logFile, "w") f.close() montior = tail.Tail(logFile) montior.register_callback(MonitorLine) obbFileName = "%s.%d.%s.obb" % (patchName, apkVersion, apkName); outFileName = outDir + "/" + obbFileName; #cmd = "java -jar jobb.jar -d %s -o %s -pn %s -pv %d" % (fileDir, outFileName, apkName, apkVersion); cmd = "jobb -d %s -o %s -pn %s -pv %d -v %s -ov" % (fileDir, outFileName, apkName, apkVersion, logFile); print cmd; #os.system(cmd); process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) while True: s = raw_input("\n是否提取生成的obb检查?(Y/N)\n") if (s != None): s.strip(); if s == 'y' or s == 'Y': dumpDir = "%s.%d.%s.dump" % (patchName, apkVersion, apkName); dumpDir = outDir + "/" + dumpDir; if (os.path.exists(dumpDir) and os.path.isdir(dumpDir)): print "正在删除目录:%s" % dumpDir; shutil.rmtree(dumpDir) cmd = "jobb -dump %s -d %s -v %s " % (outFileName, dumpDir, logFile); print cmd; process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) break elif s == 'n' or s == 'N': break; return outFileName;
def unity_export(): logger.info(' 调用UNITY打包 '.center(80, '-')) logger.info('UNITY_PATH: %s', env('UNITY_PATH')) logger.info('UNITY_LOG_PATH: %s', env('UNITY_LOG_PATH')) logger.info('UNITY_PROJECT_PATH: %s', env('UNITY_PROJECT_PATH')) logger.info('UNITY_METHOD_NAME: %s', env('UNITY_METHOD_NAME')) logger.info('EXPORT_PROJECT_PATH: %s', env('EXPORT_PROJECT_PATH')) unity_log_path = env('UNITY_LOG_PATH') logger.info('清理 unity 编译log: %s', unity_log_path) with open(unity_log_path, 'w') as fd: fd.write('') cmd = [env('UNITY_PATH'), '-quit', '-batchmode', '-logFile', env('UNITY_LOG_PATH'), '-projectPath', env('UNITY_PROJECT_PATH'), '-executeMethod', env('UNITY_METHOD_NAME'), '-outputPath', env('EXPORT_PROJECT_PATH')] # new thread to tail log file _tail = tail.Tail(unity_log_path) t = Thread(target=tail_thread, args=(_tail, )) t.start() run_cmd(cmd, 'unity打包导出', None, partial(stop_tail, _tail, t))
def add_tail(tailx, taily, taildirection, tail_nr): if taildirection == 1: offsety = 0 offsetx = -tileWidth elif taildirection == 2: offsetx = 0 offsety = tileHeight elif taildirection == 3: offsety = 0 offsetx = tileWidth else: offsetx = 0 offsety = -tileHeight newx = tailx + offsetx newy = taily + offsety tail_obj = tail.Tail(newx, newy, PLAYERC, tileWidth, tileHeight, speed) tails.append(tail_obj) if tail_nr == 1: tail_goal_positions.append(taildirection) else: tail_goal_positions.append(tail_goal_positions[-1])
def showlog(req): sess = req.session.get('username') if sess: if req.method == 'POST': input_project = projectform(req.POST) if input_project.is_valid(): pro = input_project.cleaned_data['project'] logs = tail.Tail('/export/itmanager/info/logs/a.txt' ).register_callback(print_line) return HttpResponse(logs) else: return HttpResponseRedirect('/login') projects = logpath.objects.all() input_project = projectform() count = logpath.objects.count() return render_to_response( 'showlogs.html', { 'username': sess, 'input_project': input_project, 'projects': projects, 'count': count })
#!/usr/bin/env python import tail def print_line(txt): ''' Prints received text ''' print(txt) t = tail.Tail('/root/a.txt') # Register a callback function to be called when a new line is found in the followed file. # If no callback function is registerd, new lines would be printed to standard out. t.register_callback(print_line) # Follow the file with 2 seconds as sleep time between iterations. # If sleep time is not provided 1 second is used as the default time. t.follow(s=1)
#!/usr/bin/python #coding:utf8 import tail def print_line(txt): print(txt) t = tail.Tail('/root/loglog') t.register_callback(print_line) t.follow(s=1) ##读取时间
f.close() def send(line): global GKconfig jlog = json.loads(gkparser.parselog(line)) if jlog['user'] <> 'xNull': if jlog['event'] == "Accepted": loginfailed = 0 else: loginfailed = 1 result = guardiankey.checkaccess(jlog['user'], jlog['ip'], jlog['time'], loginfailed, 'Authentication') if result['response'] == 'ACCEPT' and GKconfig['block'] == '1': f = open('/var/log/guardiankey.log', 'a') f.write(result) f.close() doAction(jlog['ip']) return result while True: if GKconfig['key'] is None: print "You need configure /etc/guardiankey/gk.conf!" quit() t = tail.Tail(GKconfig['ssh_log']) t.register_callback(callback_f) t.follow(s=1)
# def print_line(txt): # ''' Prints received text ''' # print(txt.strip()) # # t = tail.Tail('/log/testss.txt') # t.register_callback(print_line) # t.follow(s=1) # -*- coding: utf-8 -*- # import os import tail def file_name(log_dir): list1 = [] for root, dirs, files in os.walk(log_dir): list1 = files return os.path.join(os.path.dirname(os.path.realpath(__file__)), log_dir, list1[0]) # print file_name("log") def print_line(txt): print(txt).strip() t = tail.Tail(file_name("log")) t.register_callback(print_line) t.follow(s=2)
def buildFromApk(): srcApkFile = ""; while True: s = raw_input("\n请输入完整APK包文件路径:\n") if (s != None): s.strip(); if (s== None or len(s) <= 0): continue; isApk = os.path.splitext(s)[-1].lower() == ".apk"; if (not isApk): continue; srcApkFile = s; break; print "读取APK包信息..." logFile = os.path.dirname(os.path.realpath(__file__)) + "/aapt.txt"; # 如果文件不存在则重新生成 f = open(logFile, "w") f.close() montior = tail.Tail(logFile) montior.register_callback(MonitorLine) cmd = "aapt dump badging %s > %s" % (srcApkFile, logFile); # os.system(cmd); process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) # 从日志文件中读取包名和versionCode packageName, versionCode = getApkInfoFromLog(logFile); if (packageName == None or versionCode == None): print "获得APK信息失败~!" return print "读取APK信息完成..." while True: output = "\n【packageName】 %s 【versionCode】 %d 是否确认?(Y/N): " % (packageName, versionCode); s = raw_input(output); if s == 'y' or s == 'Y': break; elif s == 'n' or s == 'N': return; idx = srcApkFile.rfind('.'); if (idx < 0): return; unzipDir = srcApkFile[0:idx]; # 1.如果原来目录有文件删除掉所有文件 if (os.path.exists(unzipDir) and os.path.isdir(unzipDir)): print "正在删除目录:%s" % unzipDir; shutil.rmtree(unzipDir) #2.解压APK print "%s 开始解压APK,解压目录: %s" % (srcApkFile, unzipDir) f = zipfile.ZipFile(srcApkFile, 'r') for file in f.namelist(): s = file; s = s.decode("ascii").encode("utf-8") s = "解压=>%s" % s; print s; f.extract(file, unzipDir) f.close(); print "解压APK完成..." #3.assets/Android目录打OBB #obb目录 obboutPath = os.path.dirname(srcApkFile); obbSrcPath = "%s/assets/Android" % unzipDir; mp4Root = "%s/assets" % unzipDir; s = "%s 生成obb" % obbSrcPath; print s; #选择JOBB还是其他 obbFileName = ""; while True: s = raw_input("\n选择生成OBB方式:1.Zip生成 2.JObb生成\n"); if (s.isdigit()): cmdId = int(s) if cmdId in [1, 2]: if cmdId == 1: obbFileName = BuildObbZipFrom(obbSrcPath, obboutPath, packageName, "main", versionCode, mp4Root); break; elif cmdId == 2: obbFileName = BuildObbFrom(obbSrcPath, obboutPath,packageName, "main", versionCode); break; # 重新写入settings.xml settingsFileName = "%s/assets/bin/Data/settings.xml" % unzipDir; writeObbSettings(settingsFileName, obbFileName); #4.删除assets/Android目录 s = "%s 删除" % obbSrcPath; print s; shutil.rmtree(obbSrcPath); metaDir = "%s/META-INF" % unzipDir; s = "%s 删除" % metaDir; print s; shutil.rmtree(metaDir); #5.压缩解压删除后的,并变成JAR zipFileName = unzipDir + ".jar"; s = "重新压缩 %s" % zipFileName f = zipfile.ZipFile(zipFileName, 'w', zipfile.ZIP_DEFLATED); #for dirpath, dirnames, filenames in os.walk(unzipDir): # for file in filenames: # f.write(file, zipFileName) for path, dirnames, filenames in os.walk(unzipDir): # 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩 fpath = path.replace(unzipDir, '') for filename in filenames: s = "压缩=》%s" % filename; print s; f.write(os.path.join(path, filename), os.path.join(fpath, filename)) f.close(); print "重新压缩完成" #6.重新签名,生成新的不带assets/Android资源的APK print "开始重签名..." signApkFileName = zipFileName[0:len(zipFileName) - 4] + "_sign.apk"; AutoSignFrom(zipFileName, signApkFileName); print "生成签名APK完成" return
#!/usr/bin/env python ''' python-tail example. Does a tail follow against /var/log/syslog with a time interval of 5 seconds. Prints recieved new lines to standard out ''' import tail def print_line(txt): ''' Prints received text ''' print(txt) t = tail.Tail('/var/log/syslog') t.register_callback(print_line) t.follow(s=5)
def UnityBuildABProj(): global BuildPlatform outPath = GetUnityOrgOutPath() if (not os.path.exists(outPath)) or (not os.path.isdir(outPath)): os.mkdir(outPath) logFile = "%s/autobuild.txt" % outPath f = open(logFile, "w") f.close() montior = tail.Tail(logFile) montior.register_callback(MonitorLine) projPath = GetUnityProjPath() if (not os.path.exists(projPath)) or (not os.path.isdir(projPath)): if IsMacPlatform(): cmd = "/Applications/Unity/Unity.app/Contents/MacOS/Unity" if not os.path.exists(cmd): print "\n未安装Unity, 请下载Unity!!!" return False print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在创建工程...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" cmd = "%s -quit -batchmode -nographics -createProject %s -logFile %s" % ( cmd, projPath, logFile) process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) elif IsWindowsPlatform(): print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在创建工程...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" cmd = "Unity.exe -quit -batchmode -nographics -createProject %s -logFile %s" % ( projPath, logFile) process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) else: print "不支持此平台打包" return False cmd = "" if IsMacPlatform(): cmd = "/Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -nographics -projectPath %s -executeMethod %s -logFile " + logFile elif IsWindowsPlatform(): cmd = "Unity.exe -quit -batchmode -nographics -projectPath %s -executeMethod %s -logFile " + logFile else: print "不支持此平台打包" return False if not BuildPlatform in [0, 1, 2, 3]: return False copyCmd = cmd % (GetUnityOrgProjPath(), "AssetBundleBuild.Cmd_Build_Copy") print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在拷贝文件...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" process = subprocess.Popen(copyCmd, shell=True) montior.follow(process, 2) func = "" if BuildPlatform == 1: func = "AssetBundleBuild.Cmd_Build_Android_ABLz4_Append" elif BuildPlatform == 2: func = "AssetBundleBuild.Cmd_Build_IOS_ABLz4_Append" elif BuildPlatform == 0: func = "AssetBundleBuild.Cmd_Build_Win_ABLz4_Append" elif BuildPlatform == 3: func = "AssetBundleBuild.Cmd_Build_Mac_ABLz4_Append" else: return False cmd = cmd % (GetUnityOrgProjPath(), func) # print cmd print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>开始生成AssetBundle...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) return True
def send(line): global GKconfig jlog = gkparser_dovecot.parselog(line) if jlog['user'] <> 'xNull': if jlog['event'] == "Accepted": loginfailed = 0 else: loginfailed = 1 result = guardiankey.checkaccess(jlog['user'], jlog['ip'], jlog['time'], loginfailed, 'Authentication') if result['response'] == 'BLOCK' and GKconfig['block'] == '1': f = open('/var/log/guardiankey.log', 'a') f.write(str(json_dumps(result))) f.close() doAction(jlog['ip']) return result while True: if GKconfig['key'] is None: print "You need configure /etc/guardiankey/gk.conf!" quit() print GKdovecot['dovecot_log'] t = tail.Tail(GKdovecot['dovecot_log']) t.register_callback(callback_f) t.follow(s=1)
def gettargets(logfile, trgtdate, nlines, bufsz, newline): """Return a dict of the targets matching a given *date* in *logfile*. The dict's keys are the IP addresses corresponding to the *date* argument, and the values are dicts, with a single key consisting of the associated timestamp. """ trgts = {} trgtdatecomp = yyyymmdd.DateComp(trgtdate) finished = False nchunks = 0 # How many chunks we've processed. for chunk in tail.Tail(fpath=logfile, nlines=nlines, bufsz=bufsz, newline=newline): nchunks += 1 logger.debug('chunk %s returned from Tail, with %s lines.', nchunks, len(chunk)) for line in chunk: # Good place to log exceptions? There should be a date in every # line, except the header (first line). In practice, should only # happen at the header. Otherwise, the header may raise an error # when we call group(). dateptrns = yyyymmdd.date(line) # re.match object # We must finish the chunk before we can return. The lines in each # chunk are in order, but the chunks are in reverse order. # Therefore, the first time we come to an older date, may or may # not be its first occurrence. In other words, there may be a # variable number of lines still to go, in the current chunk, which # may be of the target date. if not dateptrns: #logger.debug('Exiting loops in gettargets. No date pattern found in line:\n' # '%s', line) finished = True else: currdatecomp = yyyymmdd.DateComp(dateptrns.group('date')) if trgtdatecomp == currdatecomp: ipaddr, tmstmp = line.split(',') ipaddr, tmstmp = ipaddr.strip('"'), tmstmp.rstrip().strip( '"') trgts[ipaddr] = {'timestamp': tmstmp} # This should be reversed. If trgtdate > currdate, it is a NEWER date. # We've gone too far, and have reached dates before trgtdate. # Finish processing the lines in the current chunk and return. elif trgtdatecomp > currdatecomp: logger.debug( 'Reached an older date (%s) than the target date (%s).', currdatecomp, trgtdatecomp) logger.debug( 'Exiting loops after current chunk is finished.') finished = True # Once we've finished the current chunk of lines. if finished: break #logger.debug('Returning %s targets.', len(trgts)) return trgts
#!/usr/bin/env python # encoding = utf-8 import tail import time import sys import stomp class MyListener(stomp.ConnectionListener): def on_error(self, headers, message): print('received an error "%s"' % message) def on_message(self, headers, message): print('received a message "%s"' % message) def send_msg(txt): conn = stomp.Connection([('192.168.238.130', 61613)]) #print 'connectioned' #conn.set_listener('', MyListener()) conn.start() conn.connect('admin', 'admin', wait=True) conn.send(body=txt, destination='/topic/HoneyPot') #print 'sended' time.sleep(1) conn.disconnect() #print 'closed' t = tail.Tail('/home/doushuo/syslog') t.register_callback(send_msg) t.follow(s=1)
def run(): t = tail.Tail( '/opt/redmine-3.4.5-0/apps/redmine/htdocs/log/production.log') t.register_callback(data) t.follow(s=3)
def diffApk(oldApkFileName, newApkFileName): if (not os.path.exists(oldApkFileName)) or (not os.path.isfile(oldApkFileName)): return False; if (not os.path.exists(newApkFileName)) or (not os.path.isfile(newApkFileName)): return False; logFile = os.path.dirname(os.path.realpath(__file__)) + "/aapt.txt"; # 如果文件不存在则重新生成 f = open(logFile, "w") f.close() montior = tail.Tail(logFile) montior.register_callback(MonitorLine) # 1.获取SrcApk的版本号 print "读取老APK包信息..." cmd = "aapt dump badging %s > %s" % (oldApkFileName, logFile); # os.system(cmd); process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) oldPackageName, oldVersionCode = getApkInfoFromLog(logFile); # 2.获取dstApk的版本号 print "读取新APK包信息..." cmd = "aapt dump badging %s > %s" % (newApkFileName, logFile); # os.system(cmd); process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) newPackageName, newVersionCode = getApkInfoFromLog(logFile); if cmp(oldPackageName, newPackageName) != 0: print ">>>oldPackageName != newPackageName<<<" return False; # 3.确认生成DIFF的ZIP包文件名 while True: s = "\n是否生成版本号 %d 到 %d的差异?(Y/N)\n" % (oldVersionCode, newVersionCode); s = raw_input(s) if (s != None): s.strip(); if s == 'y' or s == 'Y': break elif s == 'n' or s == 'N': return False; outDiffDir = os.path.dirname(os.path.realpath(newApkFileName)); diffPath = "%s/%d-%d" % (outDiffDir, oldVersionCode, newVersionCode); if (os.path.exists(diffPath) and os.path.isdir(diffPath)): print "删除目录=》%s" % diffPath; shutil.rmtree(diffPath) srcApk = zipfile.ZipFile(oldApkFileName, 'r') dstApk = zipfile.ZipFile(newApkFileName, 'r') #读取srcApk dstApk的settings.xml,读取useObb字段是否为true settingsName = "assets/bin/Data/settings.xml"; srcSetting = srcApk.getinfo(settingsName); dstSetting = dstApk.getinfo(settingsName); if srcSetting != None and dstSetting != None: print "\n检查settings.xml..." srcS = srcApk.open(srcSetting.filename); srcStr = srcS.read(); srcS.close(); dstS = dstApk.open(dstSetting.filename); dstStr = dstS.read(); dstS.close(); sRoot = ET.fromstring(srcStr); dRoot = ET.fromstring(dstStr); sUseObb = False; dUseObb = False; for node in sRoot.iter("bool"): name = node.get("name"); if name != None: name = name.lower(); if cmp(name, "useobb") == 0: text = node.text; if (text != None): text = text.lower(); if cmp(text, "true") == 0: sUseObb = True; break; for node in dRoot.iter("bool"): name = node.get("name"); if name != None: name = name.lower(); if cmp(name, "useobb") == 0: text = node.text; if (text != None): text = text.lower(); if cmp(text, "true") == 0: dUseObb = True; break; s = "srcApk使用Obb:%s dstApk使用Obb:%s" % (sUseObb, dUseObb); print s; raw_input("\n任意键继续\n"); if sUseObb and dUseObb: newApkPath = "%s_obb.jar" % diffPath; # 1.解压新版APK print "读取新Apk..." newApk = zipfile.ZipFile(newApkPath, 'w'); for info in dstApk.infolist(): s = info.filename; s = s.decode("ascii").encode("utf-8") #需要忽略新的settings.xml,后面使用老的settings.xml if (cmp(s, settingsName) == 0): continue; s = "读取=>%s" % s; print s; f = dstApk.open(info.filename); buf = f.read(); f.close(); newApk.writestr(info.filename, buf, info.compress_type) # 2.拷贝老版本APK settings.xml覆盖掉 info = srcApk.getinfo(srcSetting.filename); if info != None: print "从老Apk覆盖新Apk的settings.xml" f = srcApk.open(info.filename); buf = f.read(); newApk.writestr(info.filename, buf, info.compress_type); f.close(); newApk.close(); # 3.重新签名生成新APK newDstApkFile = "%s_obb.apk" % diffPath; AutoSignFrom(newApkPath, newDstApkFile); # 4.新生成APK作为dstApk dstApk.close(); dstApk = zipfile.ZipFile(newDstApkFile, 'r') # 开始APK内部比较,发现不一样,读取出来放到DIFF里 srcNameList = srcApk.namelist(); dstNameList = dstApk.namelist(); for dstName in dstNameList: s = dstName; s = s.decode("ascii").encode("utf-8") idx = -1; try: idx = srcNameList.index(dstName); except: idx = -1; if (idx < 0): print "src not find=》%s" % s; dstApk.extract(dstName, diffPath); else: srcName = srcNameList[idx]; srcF = srcApk.open(srcName); srcMd5 = md5sumF(srcF); srcF.close(); dstF = dstApk.open(dstName); dstMd5 = md5sumF(dstF); dstF.close(); if (cmp(srcMd5, dstMd5) != 0): print "\nDiff=》%s" % s; print "Diff Md5=> %s = %s" % (srcMd5, dstMd5); dstApk.extract(dstName, diffPath); # 生成dstApk没有的但srcApk有的文件 for srcName in srcNameList: idx = -1; try: idx = dstNameList.index(srcName); except: idx = -1; if idx < 0: s = srcName; s = s.decode("ascii").encode("utf-8") # 判断目录是否存在,如果不存在创建 if ((not os.path.exists(diffPath)) or (not os.path.isdir(diffPath))): os.makedirs(diffPath); delFileName = "%s/%s__" % (diffPath, s); delDir = os.path.dirname(delFileName) if ((not os.path.exists(delDir)) or (not os.path.isdir(delDir))): os.makedirs(delDir); print "delete file=>%s" % delFileName; f = open(delFileName, "w"); f.close(); srcApk.close(); dstApk.close(); #检测diffPath里是否有文件,如果有,则压缩 zipFile = None; zipFileName = "%s.zip" % diffPath; if (os.path.exists(diffPath) and os.path.isdir(diffPath)): for dirpath, dirnames, filenames in os.walk(diffPath): # 压缩吧 for fileName in filenames: if (zipFile == None): zipFile = zipfile.ZipFile(zipFileName, 'w', zipfile.ZIP_DEFLATED); fpath = dirpath.replace(diffPath, '') if len(fpath) > 0: if (fpath[0] == '\\' or fpath[0] == '/'): fpath = fpath[1:]; srcFileName = os.path.join(dirpath, fileName); dstFileName = os.path.join(fpath, fileName); print "%s 压缩=》%s" % (srcFileName, dstFileName); zipFile.write(srcFileName, dstFileName); if zipFile != None: zipFile.close(); print "Apk差异生成完毕..." return True;
def UnityIOSProjToIPA(): global IOSAppName logFile = "%s/autobuild.txt" % GetUnityOrgOutPath() f = open(logFile, "w") f.close() projPath = GetUnityProjPath() #生成XCode工程 cmd = "" if IsMacPlatform(): cmd = "/Applications/Unity/Unity.app/Contents/MacOS/Unity -quit -batchmode -nographics -projectPath %s -executeMethod %s -logFile " + logFile else: print "不支持此平台打包" return False montior = tail.Tail(logFile) montior.register_callback(MonitorLine) cmd = cmd % (projPath, "AssetBundleBuild.Cmd_IOS") print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在生成XCode工程...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" process = subprocess.Popen(cmd, shell=True) montior.follow(process, 2) iosExportPath = GetIOSExportProjPath() archiveFileName = "%s/%s.xcarchive" % (iosExportPath, IOSAppName) defaultIPAFileName = "%s/Unity-iPhone.ipa" % iosExportPath print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在清理XCode工程...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" # 先清理工程 #os.system("xcodebuild clean -project %s/Unity-iPhone.xcodeproj -target Unity-iPhone -configuration Release -sdk iphoneos" % iosExportPath) os.system( "xcodebuild clean -project %s/Unity-iPhone.xcodeproj -target Unity-iPhone" % iosExportPath) print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在生成archive...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" os.system( "xcodebuild archive -project %s/Unity-iPhone.xcodeproj -scheme Unity-iPhone -configuration Release -sdk iphoneos -archivePath %s" % (iosExportPath, archiveFileName)) #判断文件是否存在 if (not os.path.exists(archiveFileName)) or ( not os.path.isfile(archiveFileName)): print "\n生成archive失败~~!!!\n" return False print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>正在生成IPA...>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" print "======>>生成ad-hoc Ipa:" os.system( "xcodebuild -exportArchive -archivePath %s -exportOptionsPlist %s/build/ad-hoc.plist -exportPath %s" % (archiveFileName, iosExportPath, iosExportPath)) if (not os.path.exists(defaultIPAFileName)) or ( not os.path.isfile(defaultIPAFileName)): print "\n生成ad-hoc ipa失败~~!!!\n" return False #生成ad-hoc # IPA改名 os.rename(defaultIPAFileName, "%s/%s_ad-hoc.ipa" % (iosExportPath, IOSAppName)) #生成AppStore print "====>>生成AppStore Ipa:" os.system( "xcodebuild -exportArchive -archivePath %s -exportOptionsPlist %s/build/appstore.plist -exportPath %s" % (archiveFileName, iosExportPath, iosExportPath)) if (not os.path.exists(defaultIPAFileName)) or ( not os.path.isfile(defaultIPAFileName)): print "\n生成appstore ipa失败~~!!!\n" return False # IPA改名 os.rename(defaultIPAFileName, "%s/%s.ipa" % (iosExportPath, IOSAppName)) return True
else: print('Retry: {}'.format(current_cmd['request'])) else: print('No text, retry: {}'.format(current_cmd['request'])) else: print('No JSON') def load_intents(intentfile): f = open(intentfile, 'r') idict = json.load(f) return idict def intent_prompt(i): print('Intent:{} "{}"'.format(i['intent'], i['request'])) cmd_list = load_intents(cmd_file) cmd_iterator = iter(cmd_list) current_cmd = next(cmd_iterator) csv = open(csv_file, 'w') help() intent_prompt(current_cmd) tl = tail.Tail(file_to_watch) tl.register_callback(match_intent) tl.follow()
loglist = shlex.split(txt) req = loglist[4] req2 = req.split('=', 1)[1] req3 = req2.split()[1] # getting the log's "process time" in seconds origin_resp_time = float(loglist[3].split('=')[1])/1000000. origin_resp_status = loglist[5].split('=')[1] #print req3 #-------------------------------------------------- # Now repeat the request to the ditto server # before = datetime.now() target_url = "%(server)s%(path)s" % {'server':DITTO_TARGET, 'path':req3 } add_headers = {'Host': DITTO_TARGET_HOSTNAME} # Debug turned on # import httplib2 #httplib2.debuglevel=4 (resp, content) = Http().request(target_url, headers=add_headers) print 'got response: %s' after = datetime.now() rtime_seconds = (after - before).total_seconds() print 'origin: \t%s %s' % (origin_resp_status, origin_resp_time) print 'staging:\t%s %s\n' % (resp.status, rtime_seconds) t = tail.Tail('/var/log/httpd/coveapi_access.log') t.register_callback(process_log_line) t.follow(s=1)