在Python中,可以方便地使用os模块来运行其他脚本或者程序,这样就可以在脚本中直接使用其他脚本或程序提供的功能,而不必再次编写实现该功能的代码。为了更好地控制运行的进程,可以使用win32process模块中的函数,如果想进一步控制进程,则可以使用ctype模块,直接调用kernel32.dll中的函数.
【方式一】使用os.system()函数运行其他程序
os模块中的system()函数可以方便地运行其他程序或者脚本,模式如下:
os.system(command)
示例如下:
>>> import os
>>> os.system('notepad') # 打开记事本程序.
0
>>> os.system('notepad 1.txt') # 打开1.txt文件,如果不存在,则创建.
0
【方式二】使用ShellExecute函数运行其他程序
除了使用os.system()函数外,还可以使用win32api模块中的ShellExecute()函数来运行其他程序,格式如下:
ShellExecute(hwnd, op, file, args, dir, show)
示例如下:
>>> import win32api
>>> win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', 0) # 后台执行
>>> win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', 1) # 前台打开
>>> win32api.ShellExecute(0, 'open', 'notepad.exe', '1.txt', '', 1) # 打开文件
>>> win32api.ShellExecute(0, 'open', 'http://www.sohu.com', '', '', 1) # 打开网页
>>> win32api.ShellExecute(0, 'open', 'D:\\Opera.mp3', '', '', 1) # 播放视频
>>> win32api.ShellExecute(0, 'open', 'D:\\hello.py', '', '', 1) # 运行程序
使用ShellExecute函数,就相当于在资源管理器中双击文件图标,系统会打开相应程序运行。
NOTE:?
win32api安装?http://sourceforge.net/projects/pywin32/files/pywin32/?因我的是64的操作系统,所以下载了这个:pywin32-216.win-amd64-py2.7
【方式三】使用CreateProcess函数运行其他程序
创建进程:为了便于控制通过脚本运行的程序,可以使用win32process模块中的CreateProcess()函数创建
一个运行相应程序的进程。其函数格式为:
CreateProcess(appName, cmdLine, proAttr, threadAttr, InheritHandle, CreationFlags, newEnv, 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)
或者使用win32event.WaitForSingleObject等待创建的线程结束。函数格式如下:
WaitForSingleObject(handle, milisecond)
原文:https://www.cnblogs.com/hankleo/p/10837939.html