基于pyinstaller的自动打包单文件程序(os,shutil库练习)(1)
20230613
【使用说明】
将该程序放置在需要打包的py文件运行
【功能】
1. 自动查询当前路径下的python文件
2. 输入python文件名自动打包
【注意】
1. 非虚拟环境,打包后文件大小比较大
2. 需要据情况修改cmd_install中的命令
【代码】
import os
import shutil
class SingleFilePackage:
def __init__(self):
current_path = self.get_current_path()
current_pyfile = self.get_current_pyfile(current_path)
print(f'当前路径:{current_path}')
print(f'当前pyfile:{current_pyfile}')
packfile = input('打包文件:')
self.cmd_intaller(current_path, packfile)
self.move_exe(current_path)
self.remove_dirs(current_path, packfile)
@staticmethod
def get_current_path():
return os.getcwd()
def get_current_pyfile(self, path):
files = os.listdir(path)
pyfiles = []
for file in files:
if file[-3:] == '.py' and file != os.path.basename(__file__):
pyfiles.append(file)
return pyfiles
def cmd_intaller(self, path, packfile):
full_path = os.path.join(path, packfile)
command = f'python D:\python\Scripts\pyinstaller.exe -F {full_path}'
try:
os.system(command)
except:
print('打包失败')
else:
print('打包成功')
def move_exe(self, move_path):
move_file = os.listdir(os.path.join(move_path, 'dist'))[0]
move_file = os.path.join(move_path, 'dist', move_file)
try:
shutil.move(move_file, move_path)
except:
print('移动可执行文件成功')
def remove_dirs(self, path, file):
try:
dist = os.path.join(path, 'dist')
build = os.path.join(path, 'build')
filename = os.path.splitext(file)[0]
spec_file = os.path.join(path ,f'{filename}.spec')
except:
pass
else:
shutil.rmtree(dist)
shutil.rmtree(build)
os.remove(spec_file)
if __name__ == '__main__':
run = SingleFilePackage()