import os import sys import shutil from py_compile import compile
def clean(path): for parent, dirname, filename in os.walk(path): for dir in dirname: if dir == '__pycache__': try: fullname = os.path.join(parent, dir) shutil.rmtree(fullname) print("Success clean Folder:%s" % fullname) except Exception as e: print("Can't clean Folder:%s, reason:%s" % (fullname, e))
def compile_pyc(path): for parent, dirname, filename in os.walk(path): for cfile in filename: fullname = os.path.join(parent, cfile) if cfile[-3:] == '.py': try: if compile(fullname): if cfile != 'settings.py' and cfile != 'wsgi.py': os.remove(fullname) print("Success compile and remove file:%s" % fullname) else: print("Can't compile file:%s,The original file has been retained" % fullname) except Exception as e: print("Can't compile file:%s, reason:%s" % (fullname, e))
def move(path): for parent, dirname, filename in os.walk(path): for c_file in filename: fullname = os.path.join(parent, c_file) if c_file[-4:] == '.pyc': try: parent_path = os.path.dirname(parent) shutil.move(fullname, parent_path) print('update the dir of file successfully') except Exception as e: print("Can't move file:%s, reason:%s" % (fullname, e))
def replace_name(path): for parent, dirname, filename in os.walk(path): for c_file in filename: fullname = os.path.join(parent, c_file) if c_file[-4:] == '.pyc': try: cfile_name = '' cfile_list = c_file.split('.') version = sys.version_info replace_name = 'cpython-' + str(version[0])+str(version[1]) for i in range(len(cfile_list)): if cfile_list[i] == replace_name: continue cfile_name += cfile_list[i] if i == len(cfile_list) - 1: continue cfile_name += '.' shutil.move(fullname, os.path.join(parent, cfile_name)) print('update the name of the file successfully') except Exception as e: print("Can't remove file:%s, reason:%s" % (fullname, e))
if __name__ == '__main__': if len(sys.argv) == 3: cmd = sys.argv[1] path = sys.argv[2] if os.path.exists(path) and os.path.isdir(path): if cmd == 'clean': clean(path) elif cmd == 'move': move(path) elif cmd == 'replace_name': replace_name(path) elif cmd == 'compile_pyc': compile_pyc(path) elif cmd == 'compile': clean(path) compile_pyc(path) move(path) replace_name(path) clean(path) else: print('没有该命令') else: print("Not an directory or Direcotry doesn't exist!") else: print("在命令行中使用以下命令:") print("\tpython3 compile_pyc.py compile_pyc PATH\t\t#生成pyc文件") print("\tpython3 compile_pyc.py move PATH\t\t#移动所有pyc文件至原位置") print("\tpython3 compile_pyc.py replace_name PATH\t\t#修改文件名文件") print("\tpython3 compile_pyc.py clean PATH\t\t#清除当前项目中所有的__pycache__文件夹及以内文件") print("\tpython3 compile_pyc.py compile PATH\t\t#一键编译pyc")
|