我需要使用Python在Windows机器上打开和关闭应用程序。我试着(打开计算器(:
import subprocess, time
p = subprocess.Popen(["calc"])
time.sleep(2)
p.terminate()
也使用
p.kill()
不起作用。
然而,当(python内部(子进程终止时,应用程序在屏幕上仍然可见(计算器窗口不会关闭(。
如何打开和关闭某些应用程序(包括实际可见的窗口(?
我能够使用win32
库关闭前台的窗口:
import subprocess, time
import win32gui, win32con
for x in range(2):
# Open calculator
p = subprocess.Popen(["calc"], stdout=subprocess.PIPE, shell=True)
time.sleep(3)
# Terminate subprocess
p.terminate()
# Close window in foreground unsing win32
handler = win32gui.GetForegroundWindow()
win32gui.PostMessage(handler,win32con.WM_CLOSE,0,0)
time.sleep(3)