首页  >  文章  >  后端开发  >  如何实现 \'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