subprocess:子程序管理
阿新 • • 發佈:2021-12-27
簡介
subprocess 模組允許我們啟動一個新程序,並連線到它們的輸入/輸出/錯誤管道,從而獲取返回值。
Python3官方文件:https://docs.python.org/zh-cn/3/library/subprocess.html
使用
subprocess 模組首先推薦使用的是它的run
方法,更高階的用法可以直接使用 Popen
介面。
run()方法
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None)
- args:被用作啟動程序的引數. 可能是一個列表或字串。
- stdin、stdout 和 stderr:子程序的標準輸入、輸出和錯誤。其值可以是 subprocess.PIPE、subprocess.DEVNULL、一個已經存在的檔案描述符、已經開啟的檔案物件或者 None。subprocess.PIPE 表示為子程序建立新的管道。subprocess.DEVNULL 表示使用 os.devnull。預設使用的是 None,表示什麼都不做。另外,stderr 可以合併到 stdout 裡一起輸出。
- timeout:設定命令超時時間。如果命令執行時間超時,子程序將被殺死,並彈出 TimeoutExpired 異常。
- check:如果該引數設定為 True,並且程序退出狀態碼不是 0,則彈 出 CalledProcessError 異常。
- encoding: 如果指定了該引數,則 stdin、stdout 和 stderr 可以接收字串資料,並以該編碼方式編碼。否則只接收 bytes 型別的資料。
- shell:如果該引數為 True,將通過作業系統的 shell 執行指定的命令。
run 方法呼叫方式返回 CompletedProcess 例項,和直接 Popen 差不多,實現是一樣的,實際也是呼叫 Popen,與 Popen 建構函式大致相同,例如:
#執行ls -l /dev/null 命令 >>> subprocess.run(["ls", "-l", "/dev/null"]) crw-rw-rw- 1 root wheel 3, 2 5 4 13:34 /dev/null CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0)
returncode: 執行完子程序狀態,通常返回狀態為0則表明它已經執行完畢,若值為負值 "-N",表明子程序被終。
import subprocess
def runcmd(command):
ret = subprocess.run(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8",timeout=1)
if ret.returncode == 0:
print("success:",ret)
else:
print("error:",ret)
runcmd(["dir","/b"])#序列引數
runcmd("exit 1")#字串引數
輸出結果如下:
success: CompletedProcess(args=['dir', '/b'], returncode=0, stdout='test.py\n', stderr='')
error: CompletedProcess(args='exit 1', returncode=1, stdout='', stderr='')
Popen() 方法
Popen 是 subprocess的核心,子程序的建立和管理都靠它處理。
建構函式:
class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0,restore_signals=True, start_new_session=False, pass_fds=(),
*, encoding=None, errors=None)
常用引數:
- args:shell命令,可以是字串或者序列型別(如:list,元組)
- bufsize:緩衝區大小。當建立標準流的管道物件時使用,預設-1。
0:不使用緩衝區
1:表示行緩衝,僅當universal_newlines=True時可用,也就是文字模式
正數:表示緩衝區大小
負數:表示使用系統預設的緩衝區大小。 - stdin, stdout, stderr:分別表示程式的標準輸入、輸出、錯誤控制代碼
- preexec_fn:只在 Unix 平臺下有效,用於指定一個可執行物件(callable object),它將在子程序執行之前被呼叫
- shell:如果該引數為 True,將通過作業系統的 shell 執行指定的命令。
- cwd:用於設定子程序的當前目錄。
- env:用於指定子程序的環境變數。如果 env = None,子程序的環境變數將從父程序中繼承。
建立一個子程序,然後執行一個簡單的命令:
>>> import subprocess
>>> p = subprocess.Popen('ls -l', shell=True)
>>> total 164
-rw-r--r-- 1 root root 133 Jul 4 16:25 admin-openrc.sh
-rw-r--r-- 1 root root 268 Jul 10 15:55 admin-openrc-v3.sh
...
>>> p.returncode
>>> p.wait()
0
>>> p.returncode
Popen 物件方法
- poll(): 檢查程序是否終止,如果終止返回 returncode,否則返回 None。
- wait(timeout): 等待子程序終止。
- communicate(input,timeout): 和子程序互動,傳送和讀取資料。
- send_signal(singnal): 傳送訊號到子程序 。
- terminate(): 停止子程序,也就是傳送SIGTERM訊號到子程序。
- kill(): 殺死子程序。傳送 SIGKILL 訊號到子程序。
import time
import subprocess
def cmd(command):
subp = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8")
subp.wait(2)
if subp.poll() == 0:
print(subp.communicate()[1])
else:
print("失敗")
cmd("java -version")
cmd("exit 1")
輸出結果如下:
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
失敗
示例
ping:
# 需要匯入模組: import subprocess [as 別名]
# 或者: from subprocess import run [as 別名]
def ping(ns_name, source_lo_addr, dest_lo_addr):
try:
result = subprocess.run(['ip', 'netns', 'exec', ns_name, 'ping', '-f', '-W1',
'-c{}'.format(PING_PACKTES),
'-I', source_lo_addr, dest_lo_addr],
stdout=subprocess.PIPE)
except FileNotFoundError:
fatal_error('"ping" command not found')
output = result.stdout.decode('ascii')
lines = output.splitlines()
for line in lines:
if "packets transmitted" in line:
split_line = line.split()
packets_transmitted = int(split_line[0])
packets_received = int(split_line[3])
return (packets_transmitted, packets_received)
fatal_error('Could not determine ping statistics for namespace "{}"'.format(ns_name))
return None # Never reached
popen:
# 需要匯入模組: import subprocess [as 別名]
# 或者: from subprocess import Popen [as 別名]
def popen(cls, cmd, cwd=None, raises=False):
'''
Execute the given command string in a new process. Send data to stdin and
read data from stdout and stderr, until end-of-file is reached.
:param cls : The class as implicit first argument.
:param cwd : If it is set, then the child's current directory will be change
to `cwd` before it is executed.
:param raises : If ``True`` and stderr has data, it raises an ``OSError`` exception.
:returns : The output of the given command; pair of (stdout, stderr).
:rtype : ``tuple``
:raises OSError: If `raises` and stderr has data.
'''
parser = lambda x: [] if x == '' else [y.strip() for y in x.strip().split('\n')]
process = subprocess.Popen(cmd, shell=True, universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
# .............................trim lines and remove the empty ones
_stdout = [x for x in parser(out) if bool(x)]
_stderr = [x for x in parser(err) if bool(x)]
if _stderr and raises:
raise OSError('\n'.join(_stderr))
return _stdout, _stderr
runcmd:
import subprocess
'''
Runs a command, waits for it to complete, then returns a CompletedProcess instance.
'''
def runcmd(args,cwd=''):
ret = subprocess.run(
args=args,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding='gbk',
timeout=1
)
if ret.returncode == 0:
print("success:", ret.stdout)
else:
print("error:", ret.stderr)
if __name__ == "__main__":
runcmd(args=["dir"],cwd=r'F:\test')
Result:
# success: 驅動器 F 中的卷是 資料
# 卷的序列號是 DCBE-C50C
# F:\test 的目錄
# 2021/12/27 19:01 <DIR> .
# 2021/12/27 19:01 <DIR> ..
# 2021/08/26 22:25 15,593 AutoComplete.cs
# 2021/08/26 22:25 706 ColorRandom.cs
# 2021/08/26 22:25 6,146 DataGridViewRender.cs
# 2021/08/26 22:25 2,840 ExcelDataReader.cs
# 2021/08/26 22:25 28,050 FTPClient.cs
# 2021/08/26 22:25 404 GUID.cs
# 2021/08/26 22:25 927 ListItem.cs
# 2021/08/26 22:25 1,360 LoadXml.cs
# 2021/08/26 22:25 35,700 ManageDB.cs
# 2021/08/26 22:25 428 RadomNamed.cs
# 2021/08/26 22:25 7,380 RegexInfo.cs
# 2021/08/26 22:25 4,111 SendMail.cs
# 2021/08/26 22:25 4,250 TextAndImageColumn.cs
# 2021/08/26 22:25 1,944 TimeDelay.cs
# 14 個檔案 109,839 位元組
# 2 個目錄 56,677,851,136 可用位元組