Python win32com close excel process

Trying to change Excel_sheet to python and get completely confused during the recovery process.

import win32com.client
class XlsClass:
    def __init__(self ,filename=None ,*,Visible=False ,Alerts=False):
        self.xlApp = win32com.client.Dispatch('Excel.Application')
        self.xlApp.Visible = Visible
        self.xlApp.DisplayAlerts = Alerts
        if filename:
            self.filename = filename
            self.xlBook = self.xlApp.Workbooks.Open(filename)
        else:
            self.xlBook = self.xlApp.Workbooks.Add()
            self.filename = ''

    def __del__(self):
        self.xlBook.Close()
        self.xlApp.Quit()

Sometimes the code works well, but sometimes python raises an error like "self.xlApp.Visible can not be set?". This always happened in a loop, like:

for fname in filelist:
    xlbook = XlsClass(fname)
    #do something

Then I checked my "windowstasksmanager" and notice that

xlbook = Dispatch('Excel.Application') 

Create a process named 'EXCEL.EXE * 32'. When I type 'xlbook.Quit()', the process was still there !? So maybe there is a "can not be set" error after this residual process? After I call func 'Dispatch', how can I completely close it?

del xlbook

Impossible to kill a process the way it works?

Bad in English, waiting for help .... thanks.

================================================= =

2014/3/10: ...

Traceback (most recent call last):
  File "C:\work_daily\work_RecPy\__RecLib\XlsClass.py", line 9, in __init__
    self.xlApp.Visible = Visible
  File "C:\Program Files\python33\lib\site-packages\win32com\client\dynamic.py", 
  line 576, in __setattr__
  raise AttributeError("Property '%s.%s' can not be set." % (self._username_,attr))
AttributeError: Property 'Excel.Application.Visible' can not be set.

del self.xlApp xlbook = None XlsClass(), , , ...

+4
1

, python: XlsClass; , XlsClass , , . Excel, . :

for fname in filelist:
    xlbook = XlsClass(fname)
    #do something
    xlbook = None
    gc.collect()

:

, , .. , , . , , - :

class XlsClass:
    def __init__(self, xlApp, filename=None ,*,Visible=False ,Alerts=False):
        self.xlApp = xlApp
        self.xlApp.Visible = Visible
        ...

    def otherMethod(self):
        # ....

    def close(self):
        self.xlBook.Close()
        self.xlBook = None
        self.xlApp = None
        # don't do anything with self.xlApp or self

xlApp = win32com.client.Dispatch('Excel.Application')
for fname in filelist:
    xlbook = XlsClass(xlApp, fname)
    # do something with xlbook
    xlbook.close()

, , , __del__ .

, win32com.client.GetObject (filename), , , , ; GetObject __init__. Excel, , script, GetActiveObject (. Python/win32com - , ), a Close. win32com , Excel, script, , , , , Excel, , .

+1

Source: https://habr.com/ru/post/1530560/


All Articles