Skip to main content

清除py代码注释

# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date: 2022-07-06 22:16:38.320013
# @Last Modified by: CPS
# @Last Modified time: 2022-07-06 22:16:38.320013
# @file_path "W:\CPS\MyProject\test"
# @Filename "remove_comments.py"
# @Description: 功能描述
#
import os, sys, re
from types import coroutine

sys.path.append("..")
from os import path

INLINE_REG = re.compile(r"(.*)(#.*$)")


def main(target_path: str, skip_list: list[str] = []):
count = 0
for dir_path, dir_list, file_list in os.walk(target_path):
for each in file_list:
if each in skip_list:
continue

# *.py文件去掉注释
if each.endswith(".py"):
target = os.path.join(dir_path, each)
if os.path.exists(target):
clean_comments(target, True)
count += 1

# 处理*.pyc文件
if each.endswith(".pyc"):
target = os.path.join(dir_path, each)
os.remove(target)

# 处理__pycache__目录
clean_pycache(target_path)
print("已处理文件: ", count)


def clean_pycache(target_path: str) -> int:
"""
首先清楚所有`.pyc`文件,然后再将`__pycache__`空目录删掉

- param dir_path :{str} {description}

@returns `{ int}` {description}

"""

# 删除 __pycache__ 空目录
for dir_path, dir_list, file_list in os.walk(target_path):
for each_dir in dir_list:
if path.basename(each_dir) == "__pycache__":
target = os.path.join(dir_path, each_dir)
try:
os.rmdir(target)
except Exception as e:
print(f"删除目录失败{target}", e)


def clean_comments(file_path: str, overwirte=False) -> str:
"""
@Description {description}

- param file_path :{str} {description}
- param overwirte=False :{bool} {description}

@returns `{ str}` {description}

"""
if overwirte:
new_file = file_path
else:
new_file = os.path.join(
os.path.dirname(file_path), f"{os.path.basename(file_path)}_str"
)

with open(file_path, "r", encoding="utf-8") as f:
new_str = ""
skip = False
has_main = False
for each_line in f.readlines():
# 不稳定,需要在最后的 new_str 上遍历
# 查找行内注释
# has_inline_comment = INLINE_REG.findall(each_line)
# if len(has_inline_comment) > 0 and len(has_inline_comment[0]) == 2:
# if len(has_inline_comment[0][0].strip()) > 0:
# each_line = has_inline_comment[0][0] + "\n"

trim_str = each_line.strip()
# 过滤 """ 注释块
if trim_str.startswith('"""'):
if skip:
skip = False
continue
else:
skip = True
# 过滤 # 注释行
elif trim_str.startswith("#"):
continue

# 过滤 测试函数
elif trim_str == 'if __name__ == "__main__":':
has_main = True

if skip:
continue

if has_main:
continue

new_str += each_line

# print(new_str)
with open(new_file, "w", encoding="utf-8") as f:
f.write(new_str)


if __name__ == "__main__":
t = r"D:\CPS\MyProject\Project_Outside\PSD文件解析2\psd-tool-10-18-2\src"
main(t, ["config.py", "main.py"])