1. 用os.system打开exe
#
import os
os.system(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe")
#但是上述代码块是无法运行的,因为路径中存在空格
#由于这种方式是采用cmd的方式打开的,当路径中存在空格时无法查找到文件,因此先定位到文件夹再打开exe
os.chdir(r"C:\Program Files (x86)\Microsoft\Edge\Application")
os.system(r"msedge.exe")
2. 用os.startfile打开exe
#
import os
os.startfile(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe")
3. 利用pid关闭exe
#
import win32gui
#win32gui获取所有的pid和名称
hwnd_title = dict()
def get_all_hwnd(hwnd,mouse):
if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})
win32gui.EnumWindows(get_all_hwnd, 0)
#检测程序是否存在,若存在则关闭,关闭后在重新打开
#显示所有名称不为空的程序
for h,t in hwnd_title.items():
if t!="":
print(h,t)
#关闭某个程序
for h,t in hwnd_title.items():
if "Microsoft Edge" in hwnd_title[h]:
win32gui.SendMessage(h, win32con.WM_CLOSE)
print("成功关闭")