99热99这里只有精品6国产,亚洲中文字幕在线天天更新,在线观看亚洲精品国产福利片 ,久久久久综合网

歡迎加入QQ討論群258996829
麥子學(xué)院 頭像
蘋果6袋
6
麥子學(xué)院

Python編寫網(wǎng)頁處理腳本的方法步驟詳解

發(fā)布時間:2016-12-13 22:55  回復(fù):0  查看:2472   最后回復(fù):2016-12-13 22:55  

嵌入式web服務(wù)器不同于傳統(tǒng)服務(wù)器,web需要轉(zhuǎn)換成數(shù)組格式保存在flash中,才方便lwip網(wǎng)絡(luò)接口的調(diào)用,最近因為業(yè)務(wù)需求,需要頻繁修改網(wǎng)頁,每次的壓縮和轉(zhuǎn)換就是個很繁瑣的過程,因此我就有了利用所掌握的知識,利用python語言編寫個能夠批量處理網(wǎng)頁文件,壓縮并轉(zhuǎn)換成數(shù)組的腳本。

  腳本運(yùn)行背景(后續(xù)版本兼容)

  Python 3.5.1(下載、安裝、配置請參考網(wǎng)上教程)

  node.js v4.4.7, 安裝uglifyjs管理包,支持js文件非文本壓縮

  具體實現(xiàn)代碼如下:

  #/usr/bin/pythonimport osimport binasciiimport shutil from functools import partial

  def FileReduce(inpath, outpath):

  infp = open(inpath, "r", encoding="utf-8")

  outfp = open(outpath, "w", encoding="utf-8")

  print(outpath+" 壓縮成功")

  for li in infp.readlines():

  if li.split():

  li = li.replace('\n', '').replace('\t', '');

  li = ' '.join(li.split())

  outfp.writelines(li)

  infp.close()

  outfp.close()

  #shell命令行調(diào)用(ugllifyjs2來壓縮js文件)def ShellReduce(inpath, outpath):

  Command = "uglifyjs "+inpath+" -m -o "+outpath

  print(Command)

  os.system(Command)

  #將文件以二進(jìn)制讀取并轉(zhuǎn)化成數(shù)組保存def filehex(inpath, outpath):

  i = 0

  count = 0

  a = ''

  inf = open(inpath, 'rb');

  outf = open(outpath, 'w')

  records = iter(partial(inf.read,1), b'')

  print(outpath + " 轉(zhuǎn)換成數(shù)組成功")

  for r in records:

  r_int = int.from_bytes(r, byteorder='big')

  a += hex(r_int) + ', '

  i += 1

  count += 1

  if i == 16:

  a += '\n'

  i = 0

  a = "const static char " + outpath.split('.')[0].split('/')[-1] + "["+ str(count) +"]={\n" + a + "\n}\n\n"

  outf.write(a)

  inf.close()

  outf.close()

  #創(chuàng)建一個新文件夾def mkdir(path):

  path=path.strip()

  isExists=os.path.exists(path)

  #判斷文件夾是否存在,不存在則創(chuàng)建

  if not isExists:

  print(path+' 創(chuàng)建成功')

  os.makedirs(path)

  else:

  pass

  return path

  #刪除一個文件夾(包含內(nèi)部所有文件)def deldir(path):

  path = path.strip()

  isExists=os.path.exists(path)

  #判斷文件夾是否存在,存在則刪除

  if isExists:

  print(path + "刪除成功")

  shutil.rmtree(path)

  else:

  pass

  def WebProcess(path):

  #原網(wǎng)頁 ..\basic\

  #壓縮網(wǎng)頁 ..\reduce\

  #編譯完成.c網(wǎng)頁 ..\programe

  BasicPath = path + "\\basic"

  ProgramPath = path + "\\program"

  ReducePath = path + "\\reduce"

  #刪除原文件夾,再創(chuàng)建新文件夾

  deldir(ProgramPath)

  deldir(ReducePath)

  mkdir(ProgramPath)

  for root, dirs, files in os.walk(BasicPath):

  for item in files:

  ext = item.split('.')

  InFilePath = root + "/" + item

  OutReducePath = mkdir(root.replace("basic", "reduce")) + "/" + item

  OutProgramPath = ProgramPath + "/" + item.replace('.', '_') + '.c'

  #根據(jù)后綴不同進(jìn)行相應(yīng)處理

  #html/css 去除'\n','\t', 空格字符保留1

  #js 調(diào)用uglifyjs2進(jìn)行壓縮

  #gif jpg ico 直接拷貝

  #其它 直接拷貝

  #除其它外,剩余文件同時轉(zhuǎn)化成16進(jìn)制數(shù)組保存為.c文件

  if ext[-1] in ["html", "css"]:

  FileReduce(InFilePath, OutReducePath)

  filehex(OutReducePath, OutProgramPath)

  elif ext[-1] in ["js"]:

  ShellReduce(InFilePath, OutReducePath)

  filehex(OutReducePath, OutProgramPath)

  elif ext[-1] in ["gif", "jpg", "ico"]:

  shutil.copy(InFilePath, OutReducePath)

  filehex(OutReducePath, OutProgramPath)

  else:

  shutil.copy(InFilePath, OutReducePath)

  #獲得當(dāng)前路徑

  path = os.path.split(os.path.realpath(__file__))[0];

  WebProcess(path)

  上述實現(xiàn)的原理主要包含:

  1.遍歷待處理文件夾(路徑為..\basic,需要用戶創(chuàng)建,并將處理文件復(fù)制到其中,并將腳本放置到該文件夾上一層)-- WebProcess

  2.創(chuàng)建壓縮頁面文件夾(..\reduce, 用于存儲壓縮后文件), 由腳本完成,處理動作:

  html, css: 刪除文本中的多余空格,換行符

  js:調(diào)用uglifyjs進(jìn)行壓縮處理

  gif, jpg, ico和其它直接進(jìn)行復(fù)制處理

  3.創(chuàng)建處理頁面文件夾(..\program, 用于存儲壓縮后文件), 由腳本完成,處理動作:

  以二進(jìn)制模式讀取文件,并轉(zhuǎn)換成16進(jìn)制字符串寫入到該文件夾中

  在文件夾下(shift+鼠標(biāo)右鍵)啟用windows命令行,并輸入python web.py, 就可以通過循環(huán)重復(fù)這三個過程就可以完成所有文件的處理。

  特別注意:所有處理的文件需要以utf-8格式存儲,否則讀取時會報"gbk"讀取錯誤。

  實現(xiàn)效果如下圖

  html文件:

Python編寫網(wǎng)頁處理腳本的方法步驟詳解


    轉(zhuǎn)換數(shù)組:


Python編寫網(wǎng)頁處理腳本的方法步驟詳解


另外附送一個小的腳本,查詢當(dāng)前文件夾下文件行數(shù)和空行數(shù)(算是寫這個腳本測試時衍生出來的):

  #/usr/bin/pythonimport os

  total_count = 0;

  empty_count = 0;

  def CountLine(path):

  global total_count

  global empty_count

  tempfile = open(path)

  for lines in tempfile:

  total_count += 1

  if len(lines.strip()) == 0:

  empty_count += 1

  def TotalLine(path):

  for root, dirs, files in os.walk(path):

  for item in files:

  ext = item.split('.')

  ext = ext[-1]

  if(ext in ["cpp", "c", "h", "java", "php"]):

  subpath = root + "/" + item

  CountLine(subpath)

  path = os.path.split(os.path.realpath(__file__))[0];

  TotalLine(path)

  print("Input Path:", path)

  print("total lines: ",total_count)

  print("empty lines: ",empty_count)

  print("code lines: ", (total_count-empty_count))


來源:博客園

您還未登錄,請先登錄

熱門帖子

最新帖子

?