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.

Shin Min-Young
  • 676
  • 6
  • 6

1 Answers1

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()
Vadim Shkaberda
  • 2,807
  • 19
  • 35
  • 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? – Shin Min-Young Jan 03 '20 at 12:19
  • @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: https://stackoverflow.com/questions/2496857/is-there-a-function-in-c-that-does-the-same-as-raw-input-in-python/29636153 – Vadim Shkaberda Jan 03 '20 at 13:11