python刪除源文件中的注釋并編譯

pykde 9年前發布 | 2K 次閱讀 Python

上線需要,將py的源碼中注釋刪掉,然后編譯成字節碼。寫此腳本主要是為了刪除注釋。當然如果上線不想放py源碼,則在最后增加刪除源碼即可。

#!/bin/env python

-- coding:utf-8 --

-------------------------------

Filename:

Revision:

Date: 2012-12-3

Author: simonzhang

Email: simon-zzm@163.com

Web: www.simonzhang.net

-------------------------------

import os import re import sys import shutil import compileall

def delete_Notes(py_file):

# 原始文件只讀打開,處理文件追加打開
_tmp_sr_file = open(py_file, "rb").readlines()
_tmp_de_file = open("%s.swp" % py_file, "ab")
_skip_status = 0
_now_line = 0
_multi_count = 0
# 循環處理
for line in _tmp_sr_file:
    # 跳過前10行,因為我的開頭注釋有10行
    if _now_line > 10:
        # 獲取開頭一位和三位
        try:
            _single_row_notes = line.strip()[0]
        except:
            _single_row_notes = ""
        try:
            _multi_row_notes = line.strip()[0:3]
        except:
            _multi_row_notes = ""
        # 獲取行是否為注釋
        if _single_row_notes == "#":
            _skip_status = 1
        elif _multi_row_notes == "'''":
            if _multi_count == 0:
                _skip_status = 1
                _multi_count = 1
            else:
                _skip_status = 1
                _multi_count = 0
        elif _multi_count == 1:
            _skip_status = 1
        else:
            _skip_status = 0
    else:
        _skip_status = 0
    # 判斷是否跳過寫入
    if _skip_status == 0:
        _tmp_de_file.write(line)
    _now_line += 1
_tmp_de_file.close()
# 處理完畢將臨時文件處理為原始文件
shutil.move("%s.swp" % py_file, py_file)


def main(): _get_src_path = sys.argv[1] _get_dec_path = sys.argv[2] if os.path.exists(_get_src_path):

    # 拷貝原始文件夾
    shutil.copytree(_get_src_path, _get_dec_path)
    # 刪除原始文件中的注釋
    find_py_file = re.compile(r"^.*\.py$")
    find_walk = os.walk(_get_dec_path)
    for path,dirs,files in find_walk:
        for f in files:
            if find_py_file.search(f):
                delete_Notes("%s/%s" % (path, f))
    # 編譯成字節碼
    compileall.compile_dir(_get_dec_path)
else:
    print "Path Error!"

if name == "main": main()</pre>

 本文由用戶 pykde 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!