[Python] python删除源文件中的注释并编译 →→→→→进入此内容的聊天室

来自 , 2020-09-11, 写在 Python, 查看 150 次.
URL http://www.code666.cn/view/4f714c73
  1. #!/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # -------------------------------
  4. # Filename:    
  5. # Revision:
  6. # Date:        2012-12-3
  7. # Author:      simonzhang
  8. # Email:       simon-zzm@163.com
  9. # Web:         www.simonzhang.net
  10. # -------------------------------
  11. import os
  12. import re
  13. import sys
  14. import shutil
  15. import compileall
  16.  
  17.  
  18. def delete_Notes(py_file):
  19.     # 原始文件只读打开,处理文件追加打开
  20.     _tmp_sr_file = open(py_file, "rb").readlines()
  21.     _tmp_de_file = open("%s.swp" % py_file, "ab")
  22.     _skip_status = 0
  23.     _now_line = 0
  24.     _multi_count = 0
  25.     # 循环处理
  26.     for line in _tmp_sr_file:
  27.         # 跳过前10行,因为我的开头注释有10行
  28.         if _now_line > 10:
  29.             # 获取开头一位和三位
  30.             try:
  31.                 _single_row_notes = line.strip()[0]
  32.             except:
  33.                 _single_row_notes = ""
  34.             try:
  35.                 _multi_row_notes = line.strip()[0:3]
  36.             except:
  37.                 _multi_row_notes = ""
  38.             # 获取行是否为注释
  39.             if _single_row_notes == "#":
  40.                 _skip_status = 1
  41.             elif _multi_row_notes == "'''":
  42.                 if _multi_count == 0:
  43.                     _skip_status = 1
  44.                     _multi_count = 1
  45.                 else:
  46.                     _skip_status = 1
  47.                     _multi_count = 0
  48.             elif _multi_count == 1:
  49.                 _skip_status = 1
  50.             else:
  51.                 _skip_status = 0
  52.         else:
  53.             _skip_status = 0
  54.         # 判断是否跳过写入
  55.         if _skip_status == 0:
  56.             _tmp_de_file.write(line)
  57.         _now_line += 1
  58.     _tmp_de_file.close()
  59.     # 处理完毕将临时文件处理为原始文件
  60.     shutil.move("%s.swp" % py_file, py_file)
  61.        
  62.  
  63. def main():
  64.     _get_src_path = sys.argv[1]
  65.     _get_dec_path = sys.argv[2]
  66.     if os.path.exists(_get_src_path):
  67.         # 拷贝原始文件夹
  68.         shutil.copytree(_get_src_path, _get_dec_path)
  69.         # 删除原始文件中的注释
  70.         find_py_file = re.compile(r"^.*\.py$")
  71.         find_walk = os.walk(_get_dec_path)
  72.         for path,dirs,files in find_walk:
  73.             for f in files:
  74.                 if find_py_file.search(f):
  75.                     delete_Notes("%s/%s" % (path, f))
  76.         # 编译成字节码
  77.         compileall.compile_dir(_get_dec_path)
  78.     else:
  79.         print "Path Error!"
  80.  
  81. if __name__ == "__main__":
  82.     main()
  83. #//python/5764

回复 "python删除源文件中的注释并编译"

这儿你可以回复上面这条便签

captcha