Python的subprocess模块

时间:2022-10-18 15:19:56

尝试在Python中运行可执行文件,网上给出的解决方案是:

import os
os.system("此处填程序路径")

我要运行的程序文件名中有空格,因此果断失败了,查看了一下帮助文档,果然,在现在版本的Python中有个取代os.system的模块:subprocess!

帮助文档中是这样写的:

NAME
subprocess - subprocess - Subprocesses with accessible I/O streams FILE
c:\python27\lib\subprocess.py DESCRIPTION
This module allows you to spawn processes, connect to their
input/output/error pipes, and obtain their return codes. This module
intends to replace several other, older modules and functions, like: os.system
os.spawn*
os.popen*

顿时豁然开朗,如果要运行C盘下的文件名为“Magic Kit.exe”的程序,只需:

import subprocess
subprocess.Popen("c:/Magic Kit.exe")

就能顺利运行啦!

或者:

subprocess.Popen("notepad.exe c:/Magic Kit.exe")

可以指定使用记事本运行该程序~~