2

I'm a new beginner in python development.

I'm trying to practice win32com.client module, and there's some error that is very confused.

first, I tried it.

import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.Visible = True 

Clearly, it works well. So I tried below.

import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = True

It works like Word but closed very a few seconds later. I don't know why it happens.

4
  • Just to clarify, are you running the script or debugging it ? Commented Jan 2, 2020 at 11:30
  • I always use win32com.client.gencache.EnsureDispatch('Excel.Application') can you test if that leads to the same problem? Commented Jan 2, 2020 at 13:27
  • @ds4940 there's no error script or log because it cleary run well, but only excel was closed very soon Commented Jan 3, 2020 at 12:15
  • @tst Thank, you. This method can be one of the solution to me bro. It works well. Commented Jan 3, 2020 at 12:16

1 Answer 1

1

It looks like behaviour of Word is not as straight as it's supposed to be. Word application have to be garbage collected by gc module, but it isn't the case. You can get a superficial view terminating execution using input in interpreter:

import win32com.client
app = win32com.client.Dispatch("Excel.Application")
app.Visible = True
input('deleting reference...')
# deleting reference forces gc to clear Excel
# though Word remains uncollected even thereafter
del app
input('Exit...')

Python memory management is quite complicated and it becomes a problem when Python is embedded into other applications. Some useful information about garbage collection you can find in article How does Python manage memory? (may be outdated but could be useful for common understanding) or in Python's docs Memory Management.

The good approach is to close it explicitly using Quit method to properly release application from memory:

app.Quit()
Sign up to request clarification or add additional context in comments.

2 Comments

It works well. Thank you. I wondered that I learned the input method is like 'scanf' in C language, isn't it? But in your code, It works like 'printf', right?
@ShinMin-Young input in Python also reads the reply. I guess it's like printf and then fgets in C. Info about it could be found here: stackoverflow.com/questions/2496857/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.