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
if each.endswith(".py"):
target = os.path.join(dir_path, each)
if os.path.exists(target):
clean_comments(target, True)
count += 1
if each.endswith(".pyc"):
target = os.path.join(dir_path, each)
os.remove(target)
clean_pycache(target_path)
print("已处理文件: ", count)
def clean_pycache(target_path: str) -> int:
"""
首先清楚所有`.pyc`文件,然后再将`__pycache__`空目录删掉
- param dir_path :{str} {description}
@returns `{ int}` {description}
"""
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():
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
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"])