搜索
首页后端开发Python教程如何实现\'cat | 的并行执行zgrep\' 在 Python 中使用子进程的命令?

How to achieve parallel execution of 'cat | zgrep' commands using subprocesses in Python?

Python 中“cat”子进程的并行执行

下面的代码片段演示了多个“cat |”的顺序执行zgrep' 命令在远程服务器上,单独收集它们的输出。

<code class="python">import multiprocessing as mp

class MainProcessor(mp.Process):
    def __init__(self, peaks_array):
        super(MainProcessor, self).__init__()
        self.peaks_array = peaks_array

    def run(self):
        for peak_arr in self.peaks_array:
            peak_processor = PeakProcessor(peak_arr)
            peak_processor.start()

class PeakProcessor(mp.Process):
    def __init__(self, peak_arr):
        super(PeakProcessor, self).__init__()
        self.peak_arr = peak_arr

    def run(self):
        command = 'ssh remote_host cat files_to_process | zgrep --mmap "regex" '
        log_lines = (subprocess.check_output(command, shell=True)).split('\n')
        process_data(log_lines)</code>

但是,这种方法会导致“ssh ... cat ...”命令的顺序执行。这个问题可以通过修改代码来并行运行子进程,同时仍然单独收集它们的输出来解决。

解决方案

要在Python中实现子进程的并行执行,您可以使用“subprocess”模块中的“Popen”类。这是修改后的代码:

<code class="python">from subprocess import Popen
import multiprocessing as mp

class MainProcessor(mp.Process):
    def __init__(self, peaks_array):
        super(MainProcessor, self).__init__()
        self.peaks_array = peaks_array

    def run(self):
        processes = []
        for peak_arr in self.peaks_array:
            command = 'ssh remote_host cat files_to_process | zgrep --mmap "regex" '
            process = Popen(command, shell=True, stdout=PIPE)
            processes.append(process)

        for process in processes:
            log_lines = process.communicate()[0].split('\n')
            process_data(log_lines)</code>

此代码创建多个“Popen”进程,每个进程运行“cat |”之一。 zgrep' 命令。 'communicate()' 方法用于收集每个进程的输出,然后将其传递给 'process_data' 函数。

注意: 直接使用 'Popen' 类不会不需要显式的线程或多处理机制来实现并行性。它在同一线程内同时处理多个子进程的创建和执行。

以上是如何实现\'cat | 的并行执行zgrep\' 在 Python 中使用子进程的命令?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何使用numpy创建多维数组?如何使用numpy创建多维数组?Apr 29, 2025 am 12:27 AM

使用NumPy创建多维数组可以通过以下步骤实现:1)使用numpy.array()函数创建数组,例如np.array([[1,2,3],[4,5,6]])创建2D数组;2)使用np.zeros(),np.ones(),np.random.random()等函数创建特定值填充的数组;3)理解数组的shape和size属性,确保子数组长度一致,避免错误;4)使用np.reshape()函数改变数组形状;5)注意内存使用,确保代码清晰高效。

说明Numpy阵列中'广播”的概念。说明Numpy阵列中'广播”的概念。Apr 29, 2025 am 12:23 AM

播放innumpyisamethodtoperformoperationsonArraySofDifferentsHapesbyAutapityallate AligningThem.itSimplifififiesCode,增强可读性,和Boostsperformance.Shere'shore'showitworks:1)较小的ArraySaraySaraysAraySaraySaraySaraySarePaddedDedWiteWithOnestOmatchDimentions.2)

说明如何在列表,Array.Array和用于数据存储的Numpy数组之间进行选择。说明如何在列表,Array.Array和用于数据存储的Numpy数组之间进行选择。Apr 29, 2025 am 12:20 AM

forpythondataTastorage,choselistsforflexibilityWithMixedDatatypes,array.ArrayFormeMory-effficityHomogeneousnumericalData,andnumpyArraysForAdvancedNumericalComputing.listsareversareversareversareversArversatilebutlessEbutlesseftlesseftlesseftlessforefforefforefforefforefforefforefforefforefforlargenumerdataSets; arrayoffray.array.array.array.array.array.ersersamiddreddregro

举一个场景的示例,其中使用Python列表比使用数组更合适。举一个场景的示例,其中使用Python列表比使用数组更合适。Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

您如何在Python数组中访问元素?您如何在Python数组中访问元素?Apr 29, 2025 am 12:11 AM

toAccesselementsInapyThonArray,useIndIndexing:my_array [2] accessEsthethEthErlement,returning.3.pythonosezero opitedEndexing.1)usepositiveandnegativeIndexing:my_list [0] fortefirstElment,fortefirstelement,my_list,my_list [-1] fornelast.2] forselast.2)

Python中有可能理解吗?如果是,为什么以及如果不是为什么?Python中有可能理解吗?如果是,为什么以及如果不是为什么?Apr 28, 2025 pm 04:34 PM

文章讨论了由于语法歧义而导致的Python中元组理解的不可能。建议使用tuple()与发电机表达式使用tuple()有效地创建元组。(159个字符)

Python中的模块和包装是什么?Python中的模块和包装是什么?Apr 28, 2025 pm 04:33 PM

本文解释了Python中的模块和包装,它们的差异和用法。模块是单个文件,而软件包是带有__init__.py文件的目录,在层次上组织相关模块。

Python中的Docstring是什么?Python中的Docstring是什么?Apr 28, 2025 pm 04:30 PM

文章讨论了Python中的Docstrings,其用法和收益。主要问题:Docstrings对于代码文档和可访问性的重要性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版