首頁  >  文章  >  後端開發  >  如何實現 \'cat | 的並發執行Python 中的 zgrep\' 命令同時有效管理單一輸出以進行進一步處理?

如何實現 \'cat | 的並發執行Python 中的 zgrep\' 命令同時有效管理單一輸出以進行進一步處理?

Linda Hamilton
Linda Hamilton原創
2024-10-27 07:04:03288瀏覽

How can you achieve concurrent execution of 'cat | zgrep' commands in Python while efficiently managing individual output for further processing?

Python:「cat」子程序的並發執行

在平行處理場景中,順序執行可能是瓶頸。若要避免此問題,請探索如何執行多個 'cat | zgrep' 在 Python 中同時執行命令,同時保留單獨的輸出以進行進一步處理。

與子進程模組的並發

對於並發子進程執行而不訴諸多處理或線程,請考慮以下方法:

<code class="python">#!/usr/bin/env python
from subprocess import Popen

# Initialize processes
processes = [Popen("echo {i:d}; sleep 2; echo {i:d}".format(i=i), shell=True) for i in range(5)]

# Gather execution statuses
exitcodes = [p.wait() for p in processes]</code>

此程式碼並行啟動五個shell 指令,無需「&」或明確「.wait()」呼叫。

與執行緒池的並發

用於並發子程序輸出收集,可以使用執行緒:

<code class="python">#!/usr/bin/env python
from multiprocessing.dummy import Pool
from subprocess import Popen, PIPE, STDOUT

# Create processes
processes = [Popen("echo {i:d}; sleep 2; echo {i:d}".format(i=i), shell=True,
                   stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
             for i in range(5)]

# Collect output
def get_lines(process):
    return process.communicate()[0].splitlines()

outputs = Pool(len(processes)).map(get_lines, processes)</code>

此程式碼使用執行緒池並行收集子程序輸出。

非同步輸出收集(Python 3.8 )

在Python 3.8 中,asyncio 可用來在單一執行緒中進行並發輸出收集:

<code class="python">#!/usr/bin/env python3
import asyncio
import sys
from subprocess import PIPE, STDOUT


async def get_lines(shell_command):
    p = await asyncio.create_subprocess_shell(
        shell_command, stdin=PIPE, stdout=PIPE, stderr=STDOUT
    )
    return (await p.communicate())[0].splitlines()


async def main():
    # Concurrent command execution
    coros = [
        get_lines(
            f'"{sys.executable}" -c "print({i:d}); import time; time.sleep({i:d})"'
        )
        for i in range(5)
    ]
    print(await asyncio.gather(*coros))


if __name__ == "__main__":
    asyncio.run(main())</code>

此程式碼執行子程序並且非同步收集其輸出,從而消除了多處理或線程的需要。

以上是如何實現 \'cat | 的並發執行Python 中的 zgrep\' 命令同時有效管理單一輸出以進行進一步處理?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn