Reputation: 71
I have a code which launches an excel file on GUI. It then get updated by user and closed. This user input is later used by program. So i want my program to wait until the user closes the excel file in GUI. I tried following but it only waits for the program to open i guess.
import subprocess
loc = "C:\\Users\\Public\\Documents\\Sheet_groups.xlsx"
p = subprocess.Popen(['start',loc],stdout=subprocess.PIPE,shell = True)
p.communicate()
PS: I am new to coding world
Upvotes: 1
Views: 1668
Reputation: 841
You can use psutil (process and system utilities) to check if Excel process is still open. Try this :
import psutil
import subprocess
import time
isopen=True
loc = "C:\\Users\\Public\\Documents\\Sheet_groups.xlsx"
p = subprocess.Popen(['start',loc],stdout=subprocess.PIPE,shell = True)
time.sleep(2)
while(isopen):
isopen="EXCEL.EXE" in (p.name() for p in psutil.process_iter())
time.sleep(2)
print("File closed")
To Check if the specific windows is open you can use pywinauto library install it using.
pip install pywinauto
Then try :
import subprocess
import time
from pywinauto import Desktop
isopen=True
loc = "C:\\Users\\Public\\Documents\\Sheet_groups.xlsx"
p = subprocess.Popen(['start',loc],shell = True)
time.sleep(2)
windows = Desktop(backend="uia").windows()
while(isopen):
isopen="Sheet_groups.xlsx - Excel" in [w.window_text() for w in windows]
time.sleep(2)
print("File closed")
You can try this if you can't use pywinauto:
import subprocess
import time
import win32gui
isopen=True
loc = "C:\\Users\\Public\\Documents\\Sheet_groups.xlsx"
running=""
def winEnumHandler( hwnd, ctx ):
global running
if win32gui.IsWindowVisible( hwnd ):
running+=win32gui.GetWindowText( hwnd )
p = subprocess.Popen(['start',loc],shell = True)
time.sleep(2)
while(isopen):
isopen=win32gui.EnumWindows( winEnumHandler, None )
isopen="Sheet_groups.xlsx" in running
running=""
time.sleep(2)
print("File closed")
Upvotes: 1