国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Python標(biāo)準(zhǔn)庫 subprocess 模塊多進(jìn)程編程詳解

這篇具有很好參考價值的文章主要介紹了Python標(biāo)準(zhǔn)庫 subprocess 模塊多進(jìn)程編程詳解。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

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è)備
subprocess,高性能Python編程,python,windows,網(wǎng)絡(luò)

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):

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)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • python subprocess.run()、subprocess.Popen()、subprocess.check_output()(執(zhí)行系統(tǒng)命令、啟動新的進(jìn)程、連接到子進(jìn)程的輸入/輸出管道)

    python subprocess.run()、subprocess.Popen()、subprocess.check_output()(執(zhí)行系統(tǒng)命令、啟動新的進(jìn)程、連接到子進(jìn)程的輸入/輸出管道)

    Python的subprocess模塊是用于創(chuàng)建和管理子進(jìn)程的模塊。它提供了一種在Python中調(diào)用外部命令的方式,可以執(zhí)行系統(tǒng)命令、啟動新的進(jìn)程、連接到子進(jìn)程的輸入/輸出管道等。 subprocess.run 運(yùn)行指定的命令,并等待其完成。args參數(shù)是一個字符串或列表,表示要執(zhí)行的命令和參數(shù)。

    2024年02月09日
    瀏覽(24)
  • 【Python】系列模塊之標(biāo)準(zhǔn)庫re詳解

    【Python】系列模塊之標(biāo)準(zhǔn)庫re詳解

    ? ? 感謝點贊和關(guān)注 ,每天進(jìn)步一點點!加油! 目錄 一、Python 正則表達(dá)式 1.1 re模塊常用操作 1.2 re.match 1.3 re.search 1.4 re.findall 1.5 re.compile 函數(shù) 1.6 re.sub 檢索和替換 1.7 re.split拆分 1.8 實戰(zhàn)案例:根據(jù)文件名匹配文件并移動 Python 系列文章學(xué)習(xí)記錄: Python系列之Windows環(huán)境安裝配

    2024年02月03日
    瀏覽(25)
  • python之subprocess模塊

    subprocess模塊 Subprocess是一個功能強(qiáng)大的子進(jìn)程管理模塊,可以像Linux 系統(tǒng)中執(zhí)行shell命令那樣fork一個子進(jìn)程執(zhí)行外部的命令,subprocess 模塊允許我們啟動一個新進(jìn)程,并連接到它們的輸入/輸出/錯誤管道,從而獲取返回值。 使用subprocess模塊的目的是用于替換os.system等一些舊的

    2024年02月10日
    瀏覽(17)
  • 《Python入門到精通》os模塊詳解,Python os標(biāo)準(zhǔn)庫

    《Python入門到精通》os模塊詳解,Python os標(biāo)準(zhǔn)庫

    「作者主頁」: 士別三日wyx 「作者簡介」: CSDN top100、阿里云博客專家、華為云享專家、網(wǎng)絡(luò)安全領(lǐng)域優(yōu)質(zhì)創(chuàng)作者 「推薦專欄」: 小白零基礎(chǔ)《Python入門到精通》 OS標(biāo)準(zhǔn)庫是操作系統(tǒng)接口模塊,提供了操作系統(tǒng)相關(guān)功能的調(diào)用函數(shù)。 使用OS標(biāo)準(zhǔn)庫前,需要導(dǎo)入模塊 import

    2024年02月13日
    瀏覽(32)
  • 《Python入門到精通》time模塊詳解,Python time標(biāo)準(zhǔn)庫,time庫函數(shù)大全

    《Python入門到精通》time模塊詳解,Python time標(biāo)準(zhǔn)庫,time庫函數(shù)大全

    「作者主頁」: 士別三日wyx 「作者簡介」: CSDN top100、阿里云博客專家、華為云享專家、網(wǎng)絡(luò)安全領(lǐng)域優(yōu)質(zhì)創(chuàng)作者 「推薦專欄」: 小白零基礎(chǔ)《Python入門到精通》

    2024年02月09日
    瀏覽(20)
  • 《Python入門到精通》webbrowser模塊詳解,Python webbrowser標(biāo)準(zhǔn)庫,Python瀏覽器控制工具

    《Python入門到精通》webbrowser模塊詳解,Python webbrowser標(biāo)準(zhǔn)庫,Python瀏覽器控制工具

    「作者主頁」: 士別三日wyx 「作者簡介」: CSDN top100、阿里云博客專家、華為云享專家、網(wǎng)絡(luò)安全領(lǐng)域優(yōu)質(zhì)創(chuàng)作者 「推薦專欄」: 小白零基礎(chǔ)《Python入門到精通》 webbrowser 是Python的內(nèi)置庫,提供了訪問Web瀏覽器的接口 使用前需要 「導(dǎo)入模塊」 1)使用 「默認(rèn)瀏覽器」 打開

    2024年02月10日
    瀏覽(24)
  • Linux高性能服務(wù)器編程 學(xué)習(xí)筆記 第二章 IP協(xié)議詳解

    Linux高性能服務(wù)器編程 學(xué)習(xí)筆記 第二章 IP協(xié)議詳解

    本章從兩方面探討IP協(xié)議: 1.IP頭部信息。IP頭部出現(xiàn)在每個IP數(shù)據(jù)報中,用于指定IP通信的源端IP地址、目的端IP地址,指導(dǎo)IP分片和重組,指定部分通信行為。 2.IP數(shù)據(jù)報的路由和轉(zhuǎn)發(fā)。IP數(shù)據(jù)報的路由和轉(zhuǎn)發(fā)發(fā)生在除目標(biāo)機(jī)器外的所有主機(jī)和路由器上,它們決定數(shù)據(jù)報是否應(yīng)

    2024年02月09日
    瀏覽(31)
  • subprocess.Popen執(zhí)行程序以及關(guān)閉進(jìn)程

    python中有一個很好用的方式來開啟進(jìn)程,即 subprocess.Popen 正常來說,如果 subprocess.Popen 要執(zhí)行的腳本是一個死循環(huán)的腳本,那么我們就需要手動的來關(guān)閉這個腳本,而無法等待這個腳本自己結(jié)束。 但是這個 subprocess.Popen 在關(guān)閉腳本進(jìn)程時有一個坑。 舉例說明: python cmd= “

    2024年02月13日
    瀏覽(16)
  • 【潔潔送書第一期】Python高并發(fā)與高性能編程: 原理與實踐

    【潔潔送書第一期】Python高并發(fā)與高性能編程: 原理與實踐

    Python成為時下技術(shù)革新的弄潮兒,全民Python的發(fā)展趨勢讓人們不再滿足于簡單地運(yùn)行Python程序,逐步探索其更為廣泛的日常應(yīng)用和高性能設(shè)計。 以ChatGPT為代表的大模型產(chǎn)品對初級程序開發(fā)人員提出了挑戰(zhàn),要想在開發(fā)領(lǐng)域站穩(wěn)腳跟、有發(fā)展,必須掌握更高級的技巧和能力。

    2024年02月16日
    瀏覽(30)
  • 《Python高并發(fā)與高性能編程:原理與實踐》——小解送書第六期

    《Python高并發(fā)與高性能編程:原理與實踐》——小解送書第六期

    目錄 書籍介紹 ?抽獎 Python成為時下技術(shù)革新的弄潮兒,全民Python的發(fā)展趨勢讓人們不再滿足于簡單地運(yùn)行Python程序,逐步探索其更為廣泛的日常應(yīng)用和高性能設(shè)計。以ChatGPT為代表的大模型產(chǎn)品對初級程序開發(fā)人員提出了挑戰(zhàn),要想在開發(fā)領(lǐng)域站穩(wěn)腳跟、有發(fā)展,必須掌握更

    2024年02月14日
    瀏覽(24)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包