防止win32com结束后有excel进程残留
- import win32com.client
- import win32process,win32api,win32con
- excel = win32com.client.DispatchEx('Excel.Application')
- def close_excel_by_force(excel): # 关闭进程
-
- # Get the window's process id's
- hwnd = excel.Hwnd
- #hwnd = win32gui.FindWindowEx(0,0,None,name)
- t, p = win32process.GetWindowThreadProcessId(hwnd)
- # Ask window nicely to close
- try:
- handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
- if handle:
- win32api.TerminateProcess(handle, 0)
- win32api.CloseHandle(handle)
- except:
- pass
防止shutil删除文件时因文件属性删除失败
- import shutil
- shutil.rmtree(path,onerror=remove_readonly)
- def remove_readonly(func, path, _): # 错误回调函数,改变只读属性位,重新删除
- #"Clear the readonly bit and reattempt the removal"
- os.chmod(path, stat.S_IWRITE)
- func(path)
清空文件夹
- import shutil,os
- def clearfolder(self,path):
- if os.path.exists(path):
- shutil.rmtree(path,onerror=remove_readonly)
- time.sleep(1)
- os.makedirs(path)