python自带的compileall.compile_dir(f)方法 编译f文件夹会编译成 f/pycache/xx.cpython-36.pyc,我们期望是f/xx.pyc,于是我写了个轮子做这个事,用了递归的方法,用Path包,is_dir()来判断文件夹,iterdir()返回文件夹下的文件(迭代器)
# -*- coding: utf-8 -*-
# @Time : 2019/6/28 16:51
# @Author : zzh
# @File : my_compile.py
# @Software: PyCharm
import py_compile
import os
import sys
from pathlib import Path
import compileall
def get_files_paths():
return ['campus_platform/models.py', 'campus_platform/apps']
def compile_files(file_paths):
"""
支持递归式调用,file_paths数组(或可迭代对象)里,可以是py文件,也可以是目录,或者是path对象
file_paths 的元素可以能path对象,也可能是字符串
"""
for f in file_paths:
p = Path(f)
f = str(f)
if p.is_file() and f.endswith('py'):
py_compile.compile(f, f + 'c')
delete_ori_file(f)
print('编译文件:'+f)
# elif p.is_dir(): # 会被编译成 f/__pycache__/xx.cpython-36.pyc,期望是f/xx.pyc
# compileall.compile_dir(f)
elif p.is_dir() and not f.endswith('__pycache__'):
compile_files(p.iterdir())
def delete_ori_file(file):
# os.rename(file, '_' + file)
os.remove(file)
# 获取需要编译的py文件列表
paths = get_files_paths()
# 编译成pyc文件并删除原始py文件
compile_files(paths)