需求:将py文件批量编译,编译后删除py文件并压缩为zip文件,最后保留zip文件,其余文件及文件夹都删除。
D:\pro-compile
MPV1
TMMV1
...
D:\pro-compile\MPV1
MPV1
__init__.py
MPV1.xml
...
D:\pro-compile\MPV1\MPV1
Item01.py
Item02.py
Item03.py
Item04.py
...
~~~~~~~执行后~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
D:\pro-compile
MPV1 .zip
TMMV1.zip
...
~~~~~~~实现代码~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# -*- coding: utf-8 -*-
import compileall
import shutil
import os.path
import stat
import re
def Compile(dir):
compileall.compile_dir(dir)
def DeletePy(dir):
regexp = r”\.py$”
regexpObj = re.compile(regexp,re.M)
for parent,dirnames,filenames in os.walk(dir):
for file in filenames:
if regexpObj.search(file):
os.remove(os.path.join(parent,file))
def ZipPY(dir,rootdir):
for parent,dirnames,filenames in os.walk(dir):
for file in filenames:
if file == “__init__.pyc”:
#print(os.getcwd())
os.chdir(parent)
target = rootdir + “\\” + dirnames[0] + “.zip”
source = []
source += dirnames
source += filenames
zipCmd = ‘”C:\\Program Files (x86)\\WinRAR\\Rar.exe” a %s %s’ %(target,” “.join(source))
os.system(zipCmd)
return “success zip”
def Rmdirs(dir,rootdir):
os.chdir(rootdir)
if os.path.isdir(dir):
print(‘delete ‘ + os.path.join(rootdir,dir))
shutil.rmtree(os.path.join(rootdir,dir), True)
def main(*rootdir):
if not rootdir or rootdir[0].strip() == “”:
rootdir = ‘D:\\PM-compile’
for parent,dirnames,filenames in os.walk(rootdir):
for dir in dirnames:
dir = os.path.join(parent,dir)
Compile(dir)
print ”.join((dir,’complete compile-‘))
#path = ”.join((dir,’complete compile-‘))
DeletePy(dir)
print(”.join(‘complete delete .py files-‘))
ZipPY(dir, rootdir)
print(”.join(‘complete zip-‘))
Rmdirs(dir,rootdir)
print(dir.join(‘complete delete dir-‘))
main(‘D:\\PM-compile’)