學習自:
1~3學習自如何在python中執行另一個py文件_python_腳本之家
4~6學習自Python中四種運行其他程序的方式 - hankleo - 博客園
1、os.system方法
用法:
os.system('python3 xxx.py')
說明:
就相當於在cmd窗口中寫python3 xxx.py,即運行Python程序。
支持傳遞參數
2、execfile('xxx.py')
3、如果想要得到這個文件的輸出,可以用os.popen
4、ShellExecute
用法:
ShellExecute(hwnd, op, file, args, dir, show)
hwnd | 父窗口的句柄,如果沒有父窗口,則為0 |
op | 要運行的操作,open、print、空 |
file | 要運行的程序 |
args | 傳遞的參數 |
dir | 程序所在目錄 |
show | 是否顯示窗口 |
例子:
import win32api.ShellExecute ShellExecute(0, 'open', 'notepad.exe', '', '', 0) #show=0,后台執行 ShellExecute(0, 'open', 'notepad.exe', '', '', 1) #前台打開 ShellExecute(0, 'open', 'notepad.exe', '1.txt', '', 1)#傳入參數1.txt ShellExecute(0, 'open', 'http://www.sohu.com', '', '', 1)#打開網頁 ShellExecute(0, 'open', 'D:\\Opera.mp3', '', '', 1)#打開音頻文件,當路徑指向一個文件時 ShellExecute(0, 'open', 'D:\\hello.py', '', '', 1)#運行程序
原理:使用ShellExecute函數,相當於在資源管理器中雙擊文件圖標,系統會打開相應程序進行運行。
5、CreateProcess
顧名思義,CreateProcess即創建進程,通過win32process模塊中的CreateProcess()函數創建一個運行相應程序的進程。其函數格式為:
CreateProcess(appName,cmdLine,proAttr,threadAttr,InheritHandle,CreationFlags,newEnv,currentDir,Attr)
appName | 可執行文件名 |
cmdLine | 命令行參數 |
procAttr | 進程安全屬性 |
threadAttr | 線程安全屬性 |
InheritHandle | 繼承標志 |
CreationFlags | 創建標志 |
currentDir | 進程的當前目錄 |
Attr | 創建程序的屬性 |
舉例:
win32process.CreateProcess('C:\\Windows\\notepad.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO()) (<PyHANDLE:892>, <PyHANDLE:644>, 21592, 18780) # 函數返回進程句柄、線程句柄、進程ID以及線程ID
結束進程:win32process.TerminateProcess
TerminateProcess(handle,exitCode)
handle:要操作的進程句柄
exitCode:進程退出代碼
補充:該方法應該只能打開exe文件,打開其他文件時會報錯
6、使用ctypes調用kernel32.dll中的函數
使用ctypes模塊可以讓Python調用位於動態鏈接庫的函數。可以方便地調用由C語言編寫的動態鏈接庫,並向其傳遞參數。