subprocess模块是2.4版本中新增的模块, 它容许您生成新进程,链接到它们的 输入/输出/错误 管道,并得到它们的返回码(状态信息), 该模块的目的在于取代几个较旧的模块和功能html
官方文档 : https://docs.python.org/2/library/subprocess.html?highlight=subprocess#module-subprocesspython
subprocess 模块能够用于执行系统命令, 拿到执行的结果, 速度比较的快, 而且它容许你建立一个新的进程让其去执行另外的程序, 并与它进行通讯,获取标准的输入、标准输出、标准错误以及返回码等linux
import subprocess res = subprocess.Popen( "dir", # 在终端运行的命令 shell=True, # 新开一个终端 stdout=subprocess.PIPE, # 执行完命令, 将正确输出放到一个管道里 stderr=subprocess.PIPE, # 将错误输出放到一个管道里 ) result = res.stdout.read() # 拿到的是 bytes 格式的字符 result= str(result,encoding="gbk") # 在windows须要使用gbk编码,linux和mac上是"utf-8" print(result)
import subprocess res = subprocess.Popen( "aaa", # 在终端运行的命令 shell=True, # 新开一个终端 stdout=subprocess.PIPE, # 执行完命令, 将正确输出放到一个管道里 stderr=subprocess.PIPE, # 将错误输出放到一个管道里 ) result = res.stderr.read() # 拿到的是 bytes 格式的字符 result= str(result,encoding="gbk") # 在windows须要使用gbk编码 print(result)
import subprocess res1 = subprocess.Popen( # 开启的第一的进程 "dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) res2 = subprocess.Popen( # 开启的第二个进程 "findstr html*", shell=True, stdin=res1.stdout, # 将第一个进程的正确输出结果拿到作处理 stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) result = res2.stdout.read() result= str(result,encoding="gbk") print(result)
|
管道符号能够实现将第一个命令的结果传递给第二个命令使用import subprocess res1 = subprocess.Popen( "dir | findstr html*", # 使用管道符号运行命令 shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) result = res1.stdout.read() result= str(result,encoding="gbk") print(result)