>  기사  >  백엔드 개발  >  \'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 | 추가 처리를 위해 개별 출력을 유지하면서 Python에서 zgrep' 명령을 동시에 수행합니다.

하위 프로세스 모듈과의 동시성

멀티 프로세싱이나 스레딩에 의지하지 않고 동시 하위 프로세스 실행을 위해서는 다음 접근 방식을 고려하세요.

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

이 코드는 '&' 또는 명시적인 '.wait()' 호출 없이 5개의 셸 명령을 병렬로 실행합니다.

스레드 풀을 사용한 동시성

동시 하위 프로세스 출력 수집용 , 스레드를 사용할 수 있습니다.

<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으로 문의하세요.