在 Python 中使用 Bash 子进程进行并行处理
并行执行 bash 子进程是脚本编写和自动化中的常见任务。在 Python 中,您可以使用 subprocess 模块生成新进程,并使用 threading 模块并发执行它们。
但是,用户链接的问题的第一个答案中描述的技术会导致顺序执行bash 进程。要并行运行它们,请使用以下方法:
1.使用 multiprocessing.dummy.Pool:
对于有限数量的并发进程的并行执行,可以使用 multiprocessing.dummy.Pool。它提供了类似于 multiprocessing.Pool 的基于线程的接口。
<code class="python">import multiprocessing.dummy as mp from subprocess import call pool = mp.Pool(2) # Set the maximum number of concurrent commands for i, returncode in enumerate(pool.imap(partial(call, shell=True), commands)): if returncode != 0: print("%d command failed: %d" % (i, returncode))</code>
2.使用带有手动并发控制的子进程:
您可以在不使用线程或进程池的情况下限制并发进程的数量。
<code class="python">from subprocess import Popen from itertools import islice max_workers = 2 processes = (Popen(cmd, shell=True) for cmd in commands) running_processes = list(islice(processes, max_workers)) while running_processes: # Check for completed processes and start new ones for i, process in enumerate(running_processes): if process.poll() is not None: running_processes[i] = next(processes, None) if running_processes[i] is None: del running_processes[i] break</code>
3.通过 os.waitpid() 使用子进程(仅限 Unix):
在 Unix 系统上,您可以使用 os.waitpid(-1, 0) 来阻止并等待任何子进程退出。这消除了对繁忙循环的需要。
这些方法为使用 Python 控制 bash 子进程中的并发性提供了灵活的选项。
以上是如何与 Python 并行执行 Bash 子进程?的详细内容。更多信息请关注PHP中文网其他相关文章!

theSostCommonlyusedModuleForCreatingArraysInpyThonisnumpy.1)NumpyProvidEseffitedToolsForarrayOperations,Idealfornumericaldata.2)arraysCanbeCreatedDusingsnp.Array()for1dand2Structures.3)

toAppendElementStoApythonList,usetheappend()方法forsingleements,Extend()formultiplelements,andinsert()forspecificpositions.1)useeAppend()foraddingoneOnelementAttheend.2)useextendTheEnd.2)useextendexendExendEnd(

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

金融、科研、医疗和AI等领域中,高效存储和处理数值数据至关重要。 1)在金融中,使用内存映射文件和NumPy库可显着提升数据处理速度。 2)科研领域,HDF5文件优化数据存储和检索。 3)医疗中,数据库优化技术如索引和分区提高数据查询性能。 4)AI中,数据分片和分布式训练加速模型训练。通过选择适当的工具和技术,并权衡存储与处理速度之间的trade-off,可以显着提升系统性能和可扩展性。

pythonarraysarecreatedusiseThearrayModule,notbuilt-Inlikelists.1)importThearrayModule.2)指定tefifythetypecode,例如,'i'forineizewithvalues.arreaysofferbettermemoremorefferbettermemoryfforhomogeNogeNogeNogeNogeNogeNogeNATATABUTESFELLESSFRESSIFERSTEMIFICETISTHANANLISTS。

除了shebang线,还有多种方法可以指定Python解释器:1.直接使用命令行中的python命令;2.使用批处理文件或shell脚本;3.使用构建工具如Make或CMake;4.使用任务运行器如Invoke。每个方法都有其优缺点,选择适合项目需求的方法很重要。

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

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

热门文章

热工具

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

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

Atom编辑器mac版下载
最流行的的开源编辑器

Dreamweaver CS6
视觉化网页开发工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。