1. Subprocess模塊介紹
1.1 基本功能
- subprocess 模塊,允許生成新的進(jìn)程執(zhí)行命令行指令,python程序,以及其它語言編寫的應(yīng)用程序, 如 java, c++,rust 應(yīng)用等。
- subprocess可連接多個進(jìn)程的輸入、輸出、錯誤管道,并且獲取它們的返回碼。
- asyncio也支持subprocess.
許多知名庫都在使用此模塊創(chuàng)建進(jìn)程,以及做為跨語言粘合工具。典型如ansible, celery,selenium 等。
1.2 與multiprocessing主要區(qū)別
- multiprocessing 創(chuàng)建的子進(jìn)程的代碼也需要開發(fā)者實現(xiàn)。
- subprocess創(chuàng)建的子進(jìn)程主要用于運(yùn)行已有指令或應(yīng)用。
根據(jù)上述主要區(qū)別,不難推斷出, subprocess創(chuàng)建子進(jìn)程的用途,主要用于執(zhí)行非python的外部程序,如windows/linux 命令,C程序,Java程序等,而且可以實現(xiàn)進(jìn)程通信,多進(jìn)程管道,以及異步執(zhí)行等。
1.3 subprocess 模塊主要掌握知識點
(1)run()方法創(chuàng)建子進(jìn)程
(2)stdin, stdout,stderr 的配置,以及管道使用
(3)Popen API使用。
(4)進(jìn)程之間通信
2 使用run() 方法創(chuàng)建子進(jìn)程
2.1 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, text=None, env=None)
返回值類型:
subprocess.CompletedProcess
主要參數(shù):
- args:表示要執(zhí)行的命令。必須是以字符串為元素的 list or tuple 。
- stdin、stdout 和 stderr:子進(jìn)程的標(biāo)準(zhǔn)輸入、輸出和錯誤。其值可以是 subprocess.PIPE、subprocess.DEVNULL、一個已經(jīng)存在的文件描述符、已經(jīng)打開的文件對象或者 None。subprocess.PIPE 表示為子進(jìn)程創(chuàng)建新的管道。subprocess.DEVNULL 表示使用 os.devnull。默認(rèn)使用的是 None,表示什么都不做。
- encoding: 如果指定了該參數(shù),則 stdin、stdout 和 stderr 可以接收字符串?dāng)?shù)據(jù),并以該編碼方式編碼。否則只接收 bytes 類型的數(shù)據(jù)。
- shell:如果該參數(shù)為 True,將通過操作系統(tǒng)的 shell 執(zhí)行指定的命令。
- check: 如check=true, 當(dāng)進(jìn)程退出碼為非0時,將生成 CalledProcessError 異常
2.2 返回對象CompletedProcess的主要屬性與方法:
主要屬性:
- args 執(zhí)行指令list or tuple
- returncode 執(zhí)行完子進(jìn)程狀態(tài)碼,為0則表明它已經(jīng)運(yùn)行完畢,若值為負(fù)值 ,表明子進(jìn)程被終。 為None表示未執(zhí)行完成。
- stdout 輸出內(nèi)容,
- stderr error輸出內(nèi)容
方法 - check_returncode() 如果 returncode 是非零值, 將生成異常 CalledProcessError.
示例
>>> subprocess.run(["ls", "-l"]) # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)
>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
2.3 什么是 stdin, stdout, stderr?
OS 執(zhí)行一個shell命令,會自動打開三個標(biāo)準(zhǔn)文件:
- 標(biāo)準(zhǔn)輸入文件(stdin),通常對應(yīng)終端的鍵盤;
- 標(biāo)準(zhǔn)輸出文件(stdout), 標(biāo)準(zhǔn)錯誤輸出文件(stderr),這兩個文件都對應(yīng)終端的屏幕。
進(jìn)程的I/O操作:
- 進(jìn)程將從標(biāo)準(zhǔn)輸入文件中得到輸入數(shù)據(jù)
- 將正常輸出數(shù)據(jù)輸出到標(biāo)準(zhǔn)輸出文件,
- 將錯誤信息送到標(biāo)準(zhǔn)錯誤文件中。
標(biāo)準(zhǔn)輸入、輸出可以重定向, 從ubuntu linux為例
- 輸入重定向: wc < abc.txt, 輸入重定向為由文件讀入。
- 輸出重定向: tail a.log > abc.txt , 輸出重定向到abc.txt , >> 為追加模式
- 錯誤輸出重定向: 用 2> 文件名 表示 ,
如 python demo.py 2>&1, 將把標(biāo)準(zhǔn)錯誤輸出重定向到輸出stdout
使用“ >/dev/null ”符號,將命令執(zhí)行結(jié)果重定向到空設(shè)備中,也就是不顯示任何信息。
有時host進(jìn)程可能修改了輸入/輸出設(shè)備,subprocess將繼承,可以手工指定I/O設(shè)備
windows用run()時,args指令中前面要加cmd.exe做為執(zhí)行器
cmdTuple =(“cmd.exe”, “/C”, r"del d:\output*.png")
subprocess.run(cmdTuple)
如果運(yùn)行dos命令,前兩個參數(shù)為 “cmd.exe”, “/C”, 否則報錯。
subprocess.run([‘cmd’, ‘/C’, ‘dir D:\app’])
也可使用powshell 做執(zhí)行器, 其格式如下:
subprocess.run([“powershell”, “-Command”, “dir D:\app”])
運(yùn)行 .py文件,無須加 cmd.exe
subprocess.run([‘python’, ‘demo.py’, ‘5’]) 其中5為參數(shù)
指令也可以用字符串的形式,用shlex來解析為list
import shlex
print( shlex.split(“python subp_timer.py 5”))
subprocess.run(shlex.split(“python subp_timer.py 5”))
output:
[‘python’, ‘subp_timer.py’, ‘5’]
Starting timer of 5 seconds
…Done!
linux 使用默認(rèn)shell做為執(zhí)行器,也可以指定如用 ‘bash’
subprocess.run([“bash”, “-c”, “l(fā)s /usr/bin | grep pycode”])
3.Pipe 使用
Pipe 即管道,可以將兩個進(jìn)程連接起來:上1個進(jìn)程的stdout 可以做為下1個進(jìn)程的輸入
cp1 = subprocess.run(
['cmd.exe','/C','dir /A:D /B','D:\workplace'],
stdout=subprocess.PIPE
)
print(cp1.stdout.decode('utf-8'))
cp2 = subprocess.run(
['cmd.exe','/C','find','/I','\"python\"'],
input=cp1.stdout,
stdout=subprocess.PIPE
)
print(cp2)
4.Popen API 使用
Popen 是 subprocess的核心,底層的子進(jìn)程的創(chuàng)建和管理都靠它處理,它支持主程序與子進(jìn)程之間通信。 run()方法只能用于一些簡單場合,Popen()更加方便。
4.1 Popen對象的構(gòu)造函數(shù):
class subprocess.Popen(args, bufsize=-1, stdin=None, stdout=None, stderr=None,
shell=False, cwd=None, env=None, *, encoding=None)
常用參數(shù):
- args:shell命令,可以是字符串或者序列類型(如:list,元組)
- bufsize:緩沖區(qū)大小。當(dāng)創(chuàng)建標(biāo)準(zhǔn)流的管道對象時使用,默認(rèn)-1。 0:不使用緩沖區(qū) 1:表示行緩沖,僅當(dāng)universal_newlines=True時可用,也就是文本模式 正數(shù):表示緩沖區(qū)大小 負(fù)數(shù):表示使用系統(tǒng)默認(rèn)的緩沖區(qū)大小。
- stdin, stdout, stderr:分別表示程序的標(biāo)準(zhǔn)輸入、輸出、錯誤句柄
- shell:如果該參數(shù)為 True,將通過操作系統(tǒng)的 shell 執(zhí)行指定的命令。通常使用False
- cwd:用于設(shè)置子進(jìn)程的當(dāng)前目錄。
- env:用于指定子進(jìn)程的環(huán)境變量。如果 env = None,子進(jìn)程的環(huán)境變量將從父進(jìn)程中繼承。
- encoding 為stdout的編碼,指定后,可自動將bytes內(nèi)容轉(zhuǎn)為字符串
創(chuàng)建一個子進(jìn)程,然后執(zhí)行一個簡單的命令:
實例
>>> 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(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
4.2 Popen 對象支持context
with Popen(["ifconfig"], stdout=PIPE) as proc:
log.write(proc.stdout.read())
4.3 Popen對象的方法與屬性
- Popen.poll()
檢查子進(jìn)程是否已被終止。設(shè)置并返回returncode 屬性。否則返回 None。 - Popen.wait(timeout=None)
等待子進(jìn)程被終止。設(shè)置并返回returncode 屬性。
如果進(jìn)程在 timeout 秒后未中斷,拋出一個TimeoutExpired 異常,可以安全地捕獲此異常并重新等待。 - Popen.communicate(input=None, timeout=None) 與進(jìn)程交互:將數(shù)據(jù)發(fā)送到 stdin。從 stdout 和 stderr 讀取數(shù)據(jù),
communicate() 返回一個 (stdout_data, stderr_data) 元組。如果文件以文本模式打開則為字符串;否則為字節(jié)串。
proc = subprocess.Popen(...)
try:
outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
- Popen.send_signal(signal) 發(fā)送OS信號
- Popen.terminate(), Popen.kill() 終止、殺死進(jìn)程
屬性:
args, stdin, stdout, stderr, pid, returncode
4.5 Popen.stdout的編碼問題
stdout值為bytes 類型,查看時通常需要轉(zhuǎn)為str, 但windows 命令返回的stdout編碼類型可能不是utf-8. 需要使用chardet.detect( bytes_obj) 來檢測
import chardet
import subprocess
cmd = ['cmd.exe','/C', 'ipconfig']
pp = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out: bytes = pp.stdout.read()
encode = chardet.detect(out)['encoding']
print(encode)
print(out.decode(encode))
output:
PS D:\workplace\python\test1\multi_thread> py subp_2.py
GB2312
Windows IP 配置
...
5. 與子進(jìn)程的通信
5.1 向子進(jìn)程輸入數(shù)據(jù)
方式1: 通過communicate(input=bytes_obj) 輸入?yún)?shù)
process = subprocess.Popen(['cmd', '/C', 'findstr','example'], stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# 使用input參數(shù)傳遞輸入
input_data = b"Some input\n subprocess \n example line"
out, err = process.communicate(input=input_data)
print(out)
方式2: 通過Pipe向子進(jìn)程輸入數(shù)據(jù): process.stdin.write()
process = subprocess.Popen(['cmd', '/C', 'findstr','example'], stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# Write to the subprocess's standard input
process.stdin.write(b'first line \n 2:some example input\n third line\n')
# Close the input stream
process.stdin.close()
out, err = process.communicate()
print(out, err)
3)獲取子進(jìn)程的輸出內(nèi)容
方式1: 使用 process.communicate() 方法獲取 output 與 error
out, err = process.communicate(), out, err 均為bytes 類型
方式2: 直接讀 process.stdout 屬性, 方式與讀文件相同,
line = process.stdout.readline()
content = process.stdout.read()
示例
# 讀取子進(jìn)程的輸出
cmd = ["ping", "baidu.com"]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
counter = 0
while True:
# Read a line from the subprocess's stdout
line = process.stdout.readline()
# Check if the line is empty, indicating that the subprocess has finished
if not line :
break
if counter > 3:
print(f"terminate process {process.pid}")
process.terminate() # 強(qiáng)行終止進(jìn)程
break
counter += 1
print(process.poll()) # 檢查進(jìn)程是否結(jié)束
# Process and print the line
print(line, end='')
# Wait for the subprocess to finish and get its return code
return_code = process.wait(2)
print(f"Subprocess returned with exit code: {return_code}")
print(process.poll())
6. 子進(jìn)程的異步執(zhí)行
asyncio異步模塊也提供了 subprocess 類, 好處是避開了GIL鎖的限制, 運(yùn)行速度顯著提高
import asyncio
async def run(cmd):
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
print(f'[{cmd!r} exited with {proc.returncode}]')
if stdout:
print(f'[stdout]\n{stdout.decode()}')
if stderr:
print(f'[stderr]\n{stderr.decode()}')
async def main():
await asyncio.gather(
run('python subp_timer.py 2'),
)
asyncio.run(main())
7. 其它功能
7.1 異常處理
子進(jìn)程可能會遇到各種問題,建議使用如下處理異常的代碼結(jié)構(gòu):文章來源:http://www.zghlxwxcb.cn/news/detail-787275.html
import subprocess
try:
cmd = ["your_command_here"]
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True)
stdout, stderr = process.communicate()
print(stdout,stderr)
except subprocess.CalledProcessError as e:
print(f'Subprocess failed with return code {e.returncode}')
except FileNotFoundError:
print('Command not found')
7.2 常見問題排查
(1)命令不能運(yùn)行,通常是args 列表有問題。 可先在terminal 測試
(2)命令行處理的文件與當(dāng)前目錄不同,
(3)進(jìn)程block問題文章來源地址http://www.zghlxwxcb.cn/news/detail-787275.html
- communicate()方法是block方法,如果子進(jìn)程未結(jié)束,運(yùn)行communicate()會造成進(jìn)程block, 應(yīng)該使用stdout.read()來讀取中間內(nèi)容。
- 如果進(jìn)程有輸入,需要注意提供輸入stdin.write()
到了這里,關(guān)于Python標(biāo)準(zhǔn)庫 subprocess 模塊多進(jìn)程編程詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!