Like many other people, I am having trouble getting rid of all the excel processes when I run excel operations through a python script. Now I am down to one lingering process.
I did an earlier post, but I have since done some more testing, and I have manage to reduce the script.
Some of the things I tested can be seen in the old post here: Excel background process not closing after running python script
My current script is:
import clr
clr.AddReferenceByName(‘Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c’)
from Microsoft.Office.Interop import Excel
from System.Runtime.InteropServices import Marshaldef tolist(obj1):
if isinstance(obj1,list):
return obj1
else:
return [obj1]path = IN[0]
macroName = IN[1]
solverPath = IN[2]
data = tolist(IN[3])
incell = IN[4]
outcell_start = IN[5]
outcell_end = IN[6]
sheetname = IN[7]out_list=
for i in range(len(data)):
ex = Excel.ApplicationClass()
ex.Visible = False
ex.DisplayAlerts = False
ex.ScreenUpdating = Falseworkbook = ex.Workbooks.Open(path)
ws = workbook.Worksheets(sheetname)sol = Excel.ApplicationClass()
sol.Visible = False
sol.DisplayAlerts = False
sol.ScreenUpdating = Falseex.AddIns(“Solver Add-in”).Installed = True
solver = sol.Workbooks.Open(solverPath)
out_bf=ws.Range[outcell_start,outcell_end].Value2
if ws.Range[incell].Value2 == data[i]:
#Effectively → Do nothing
out_af=out_bfelse:
ws.Range[incell].Value2 = data[i]
ex.Run(macroName)#The workbook and solver is closed
workbook.Close(True)solver.Close(False)
sol.ScreenUpdating = Truesol.Quit()
Marshal.ReleaseComObject(ws)
Marshal.ReleaseComObject(solver)
Marshal.ReleaseComObject(workbook)
Marshal.ReleaseComObject(sol)#The workbook is reopened to collect output
workbook = ex.Workbooks.Open(path)
ws = workbook.Worksheets(sheetname)out_af=ws.Range[outcell_start,outcell_end].Value2
out_list.append(out_af)workbook.Close(True)
ex.ScreenUpdating = Trueex.Quit()
Marshal.ReleaseComObject(ws)
Marshal.ReleaseComObject(workbook)
Marshal.ReleaseComObject(ex)OUT=out_list
My guess is that there is a COM object which I have not released, but I can’t figure out which.