🍖subprocess 模块

一.引入

subprocess模块是2.4版本中新增的模块, 它允许您生成新进程,连接到它们的 输入/输出/错误 管道,并获得它们的返回码(状态信息), 该模块的目的在于取代几个较旧的模块和功能

  • os.system
  • os.spawn*
  • os.popen*
  • popen2.*
  • commands.*

官方文档 : https://docs.python.org/2/library/subprocess.html?highlight=subprocess#module-subprocess

一. subprocess模块的简单使用

subprocess 模块可以用于执行系统命令, 拿到执行的结果, 速度比较的快, 并且它允许你创建一个新的进程让其去执行另外的程序, 并与它进行通信,获取标准的输入、标准输出、标准错误以及返回码等

1.简单执行命令拿到结果

  • 先来一个正确执行命令
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)
  • 执行正确结果

image-20210113171143223

  • 那如果你输入的命令不存在, stdout 改成 stderr
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)
  • 执行错误结果

image-20210113171540688

2.将第一次执行命令拿到的结果进行第二次操作

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)
  • 运行结果 (成功)

image-20210113210737742

3.直接一条终端命令实现上面的操作

  • 通过 | 管道符号可以实现将第一个命令的结果传递给第二个命令使用
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)
  • 运行结果一样

image-20210113211202387

原文地址:https://www.cnblogs.com/songhaixing/p/14275042.html