🍖subprocess 模塊

一.引入

subprocess模塊是2.4版本中新增的模塊, 它容許您生成新進程,鏈接到它們的 輸入/輸出/錯誤 管道,並得到它們的返回碼(狀態信息), 該模塊的目的在於取代幾個較舊的模塊和功能html

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

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

一. subprocess模塊的簡單使用

subprocess 模塊能夠用於執行系統命令, 拿到執行的結果, 速度比較的快, 而且它容許你建立一個新的進程讓其去執行另外的程序, 並與它進行通訊,獲取標準的輸入、標準輸出、標準錯誤以及返回碼等linux

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

相關文章
相關標籤/搜索