python删除注释_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()

标签:

脚本

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com

特别注意:本站所有转载文章言论不代表本站观点!

本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值