Python subprocess: 打开一个程序并等待用户保存并关闭它

Python subprocess: Open a program and wait for user to save and close it

我有一个代码可以在 GUI 上启动一个 excel 文件。然后由用户更新并关闭。该用户输入稍后由程序使用。所以我希望我的程序等到用户在 GUI 中关闭 excel 文件。 我试过跟随,但我猜它只等待程序打开。

import subprocess
loc = "C:\Users\Public\Documents\Sheet_groups.xlsx"
p = subprocess.Popen(['start',loc],stdout=subprocess.PIPE,shell = True)
p.communicate()

PS: 我是编程新手

您可以使用 psutil(进程和系统实用程序)检查 Excel 进程是否仍处于打开状态。试试这个:

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")

要检查特定 windows 是否打开,您可以使用 pywinauto 库安装它。

pip install pywinauto

然后尝试:

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")

不会用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")