概述
python 提供3个库来启动、调用程序:
- os.system(),简单好用,但功能弱
- os.popen()
- subprocess库,功能强大但复杂,参见http://www.malaoshi.top/show_1C7l3X6kPi.html
- 使用win32api
- commands在python3被废弃,建议使用subprocess
os.system()
返回command命令执行完毕后的退出状态(成功为0),如果command有执行内容,会在标准输出显示。这实际上是使用C标准库函数system()实现的。
阻塞 模式运行
代码
#coding=utf-8
import os
i=os.system("ping baidu.com")
print('结果:',i)
执行结果
正在 Ping malaoshi.top [101.200.162.40] 具有 32 字节的数据:
来自 101.200.162.40 的回复: 字节=32 时间=51ms TTL=113
来自 101.200.162.40 的回复: 字节=32 时间=55ms TTL=113
来自 101.200.162.40 的回复: 字节=32 时间=50ms TTL=113
来自 101.200.162.40 的回复: 字节=32 时间=50ms TTL=113
101.200.162.40 的 Ping 统计信息:
数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 50ms,最长 = 55ms,平均 = 51ms
结果: 0
缺点:无法保存command命令的执行结果。
2.os.popen
参见 https://www.malaoshi.top/show_1EF4dUL8SF5U.html
3.win32api
启动应用程序脚本
#coding=utf-8
import win32api
#日报软件启动
win32api.ShellExecute(0, 'open', r'C:\Program Files\Pudding\Pudding.exe', '','',1)
#OA启动
win32api.ShellExecute(0, 'open', r'C:\Program Files\Tongda\ispirit\ispiritPro.exe', '','',1)
#QQ启动
win32api.ShellExecute(0, 'open', r'D:\QQ\Bin\QQ.exe', '','',1)
终止应用程序脚本
#coding=utf-8
import os
#终止QQ软件
os.system("taskkill /F /IM QQ.exe")
#终止日报订餐软件
os.system("taskkill /F /IM Pudding.exe")
#终止OA软件
os.system("taskkill /F /IM ispiritPro.exe")
4.subprocess
参见 http://www.malaoshi.top/show_1C7l3X6kPi.html