简体   繁体   English

如何在Python中运行一系列异步Shell脚本

[英]How to run a sequence of asynchronous shell scripts in Python

I have a nodejs script using parallel async calls with callbacks in order to execute a series of shell scripts in the order they need to be run. 我有一个使用带有回调的并行异步调用的nodejs脚本,以便按需要运行的顺序执行一系列shell脚本。 (Data analysis tasks which are dependent on the numbers being crunched by the previous steps) (数据分析任务取决于前面步骤处理的数字)

pseudo-code nodejs example: 伪代码nodejs示例:

async.parallel([
  async.apply('/usr/local/bin/foo some/path/to/some/script.sh 1'),
  async.apply('/usr/local/bin/foo some/path/to/some/script.sh 2'),
], function () {
  async.parallel([async.apply('/usr/local/bin/foo some/path/to/some/script.sh 3')];
});

So it would run the first two at the same time and when they've both completed, run the next ones. 因此它将同时运行前两个,当它们都完成时,运行下一个。 In reality this is many levels deep. 实际上,这有很多层次。 I'm looking to replace this with a Python version but am struggling to figure out which modules/packages to leverage to make it happen. 我正在尝试将其替换为Python版本,但仍在努力找出可以利用哪些模块/软件包来实现它。

Searches have brought up numerous possible ways to do this in Python which is making it a bit tricky to suss out which one to go for. 搜索已经提出了许多可能的方法来用Python做到这一点,这使得很难确定要使用哪种方法。 Asyncio, subprocess, etc. 异步,子进程等

You could use multiprocessing and subprocess modules 您可以使用多处理子处理模块

from multiprocessing import Pool
from subprocess import call

Pool(2).map(call, [
    ["/usr/local/bin/foo some/path/to/some/script.sh", "1"],
    ["/usr/local/bin/foo some/path/to/some/script.sh", "2"]
])

call(["/usr/local/bin/foo some/path/to/some/script.sh", "3"])

Pool.map will call a function (the first argument) with each element of the array (the second argument) asynchronously. Pool.map将与数组的每个元素(第二个参数)异步调用一个函数(第一个参数)。 Once all of the calls are finished it will return a list with results (not used in this case) and code will continue executing as usual. 一旦完成所有调用,它将返回一个带有结果的列表(在这种情况下不使用),并且代码将照常执行。 So the third script will run once the first two are completed 因此,前两个完成后,第三个脚本将运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM