使用ShellExecute函式執行其他程式 ——轉載
10.4.2 使用ShellExecute函式執行其他程式
除了使用os模組中的os.system()函式以外,還可以使用win32api模組中的ShellExecute()函式。其函式如下所示。
ShellExecute(hwnd, op , file , params , dir , bShow )
其引數含義如下所示。
hwnd:父視窗的控制代碼,如果沒有父視窗,則為0。
op:要進行的操作,為“open”、“print”或者為空。
file:要執行的程式,或者開啟的指令碼。
params:要向程式傳遞的引數,如果開啟的為檔案,則為空。
dir:程式初始化的目錄。
bShow:是否顯示視窗。
以下例項使用ShellExecute函式執行其他程式。
>>> import win32api
# 開啟記事本程式,在後臺執行,即顯示記事本程式的視窗
>>> win32api.ShellExecute(0, 'open', 'notepad.exe', '','',0)
# 開啟記事本程式,在前臺執行
>>> win32api.ShellExecute(0, 'open', 'notepad.exe', '','',1)
# 向記事本傳遞引數,開啟python.txt
>>> win32api.ShellExecute(0, 'open', 'notepad.exe', 'python.txt','',1)
# 在預設瀏覽器中開啟http://www.python.org網站
>>> win32api.ShellExecute(0, 'open', 'http://www.python.org', '','',1)
# 在預設的媒體播放器中播放E:\song.wma
>>> win32api.ShellExecute(0, 'open', 'E:\\song.wma', '','',1)
# 執行位於E:\book\code目錄中的MessageBox.py指令碼
>>> win32api.ShellExecute(0, 'open', 'E:\\book\\code\\MessageBox.py', '','',1)
可以看出,使用ShellExecute函式,就相當於在資源管理器中雙擊檔案圖示一樣,系統會開啟相應的應用程式執行操作。