import os, shutil
import compileall
def copy_to_up(path):
for f in os.listdir(path):
if f == '__pycache__':
for f_main in os.listdir(os.path.join(path, f)):
path_src = os.path.join(path, f)
shutil.copy(os.path.join(path_src,f_main),path) #copy src up to path
filePath = os.path.join(path, f)
if os.path.isfile(filePath):
os.remove(filePath)
print("[kongdejing debug] " + filePath + " was removed!") #delete file
elif os.path.isdir(filePath):
shutil.rmtree(filePath,True)
print("[kongdejing debug] " + "Directory: " + filePath +" was removed!") #delete directory
def rename_file(path):
for f in os.listdir(path):
if f.endswith('.pyc'):
f_new = f.replace('.cpython-39','')
os.rename(os.path.join(path, f), os.path.join(path, f_new))
def copy_rename(f, path):
# 如果是__pycache__ 文件夹 将其中的文件移至上一层
if f == '__pycache__':
copy_to_up(path)
#当前层为.pyc文件重命名
rename_file(path)
for pyf in os.listdir(path):
if pyf.endswith('.py') and not os.path.isdir(os.path.join(path, pyf)):
os.remove(os.path.join(path, pyf))
def recursion_search(path):
for f_d in os.listdir(path):
copy_rename(f_d, path)
if os.path.isdir(os.path.join(path, f_d)):
path_d_d = os.path.join(path, f_d)
recursion_search(path_d_d)
def py_to_pyc(path):
for f in os.listdir(path):
copy_rename(f, path)
if f != 'env' and f!='.vscode' and os.path.isdir(os.path.join(path, f)):
path_d = os.path.join(path, f)
print(path_d)
recursion_search(path_d)
if __name__ == '__main__':
path = r'./docker_release'
# path = r'./test'
compileall.compile_dir(path, force=True)
py_to_pyc(path)
参考文献:https://www.jianshu.com/p/325682b5350f
网友评论