subprocess 官網:
subprocess
使用方式
run()方法來實現子程序呼叫優先選用
popen()雖然強大但是存在阻塞問題
run()
import subprocess
import shlex
# 需要執行的命令
command_line = "ls -al /usr"
# 命令格式化
args = shlex.split(command_line)
# 執行命令程序
a=subprocess.run(args,shell=true,stdout=subprocess.pipe)
# 列印命令輸出的資訊
print(str(a.stdout.decode(encoding='utf-8')))
popen()
subprocess.popen(args, bufsize=0, executable=none, stdin=none, stdout=none, stderr=none, preexec_fn=none, close_fds=false, shell=false, cwd=none, env=none, universal_newlines=false, startupinfo=none, creationflags=0)
import subprocess
import shlex
# 需要執行的命令
command_line = "ls -al /usr"
# 命令格式化
args = shlex.split(command_line)
# 執行命令程序
run=subprocess.run(args,shell=true,stdout=subprocess.pipe)
# 等待程序結束
run.wait()
# 返回狀態
print(str(run.returncode))
run.kill()
殺死這個子程序。
run.stdin
在建立run物件時,引數stdin設定為subprocess.pipe時run.stdin會返回乙個檔案物件用於對這個子程序傳送指令。否則返回none。
run.stdout
在建立run物件時,引數stdout設定為subprocess.pipe時run.stdout將返回乙個檔案物件來返回子程序執行結果資訊,否則返回 none。
run.stderr
如果在建立popen物件是,引數stdout被設定為pipe,popen.stdout將返回乙個檔案物件來返回子程序執行失敗的錯誤資訊。否則返回 none。
run.pid
獲取子程序的程序id。
run.poll()
用於檢查子程序是否已經結束,設定並返回returncode屬性。
run.wait()
等待子程序結束,設定並返回returncode屬性
run.returncode
獲取程序的返回值,如果程序還沒有結束,返回none
struct 模組 subprocess 模組
struct 模組 就這麼用 import struct 首先匯入此模組 res ncjewgfjsdbvdhj 隨意的值 print len res 15 只是為了展示原res的長度res1 struct.pack i len res 打包,固定i模式,len res print len res1...
subprocess模組 re模組
import subprocess 匯入subprocess模組,該模組的作用為可以通過python 向終端 cmd 傳送命令 while true 進行迴圈,可以讓使用者重複的進行輸入 cmd str input 請輸入終端命令 strip 定義變數cmd str obj subprocess.p...
使用subprocess模組非同步併發執行遠端命令
運維自動化平台不可避免地會涉及到遠端命令執行操作,主要分為兩類主要做法 目標機器安裝agent,或者使用ssh。saltstack是乙個典型的agent模式的遠端控制工具,麻煩的地方是首先要在目標機器上安裝saltstack的agent。使用ssh的模組居多,fabric和ansible是此類工具中...