python - 在 bash 中使用 xargs 进行并行处理

标签 python bash openstack xargs

我有一个小脚本,我可以在其中获取每个 openstack 的租户并在 python 的帮助下获取一些输出。生成报告的时间太长,建议我使用 xargs。我之前的代码如下所示。

#!/bin/bash
cd /scripts/cloud01/floating_list

rm -rf ./reports/openstack_reports/
mkdir -p ./reports/openstack_reports/

source ../creds/base
for tenant in A B C D E F G H I J K L M N O P Q R S T
do
  source ../creds/$tenant
  python ../tools/openstack_resource_list.py > ./reports/openstack_reports/$tenant.html

done
lftp -f ./lftp_script

现在我将 xargs 放入脚本中,脚本看起来像这样。

#!/bin/bash
cd /scripts/cloud01/floating_list

rm -rf ./reports/openstack_reports/
mkdir -p ./reports/openstack_reports/

source ../creds/base

# Need xargs idea below
cat tenants_list.txt | xargs -P 8 -I '{}' # something that takes the tenant name and source
TENANT_NAME={}
python ../tools/openstack_resource_list.py > ./reports/openstack_reports/$tenant.html
lftp -f ./lftp_script

在这个脚本中,我应该如何实现 source ../creds/$tenant?因为在处理每个租户的同时,还需要获取它的来源,而且我不确定如何将其包含在 xargs 中以进行并行执行。

最佳答案

xargs无法轻松运行 shell 函数...但它可以运行 shell。

# If the tenant names are this simple, don't put them in a file
printf '%s\n' {A..T} |
xargs -P 8 -I {} bash -c 'source ../creds/"$0"
      python ../tools/openstack_resource_list.py > ./reports/openstack_reports/"$0".html' {}

有点晦涩,bash -c '...' 之后的论点暴露为 $0在脚本中。

如果您想将租户保存在一个文件中,xargs -a filename是避免 useless use of cat 的好方法,虽然它不能移植到所有 xargs实现。 (使用 xargs ... <filename 重定向显然是完全可移植的。)

为了提高效率,您可以重构脚本以遍历尽可能多的参数:

printf '%s\n' {A..T} |
xargs -n 3 -P 8 bash -c 'for tenant; do
      source ../creds/"$tenant"
      python ../tools/openstack_resource_list.py > ./reports/openstack_reports/"$tenant".html
  done' _

这将运行最多 8 个并行 shell 实例,每个实例最多分配 3 个租户(因此实际上只有 7 个实例),尽管参数数量很少,性能差异可能可以忽略不计。

因为我们现在实际上收到了一个参数列表,所以我们传递了 _作为填充 $0 的值with(只是因为它需要设置一些东西,以便正确地获得真正的参数)。

如果source可能会做出并不总是保证被 source 覆盖的修改在下一次迭代中(比如,一些租户有一些变量需要为其他一些租户取消设置?)这会使事情复杂化,但如果你真的需要帮助解决这个问题,可能会发布一个单独的问题;或者只是退回到第一个变体,其中每个租户都在单独的 shell 实例中运行。

关于python - 在 bash 中使用 xargs 进行并行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47937446/

相关文章:

linux - 如果找到模式,如何使用 awk 打印 "hello"

linux - 在 openstack 上使用 ansible 实现网络自动化

python - 将云高仪输出转换为 python 数据帧

java - 如何使用 JOSS 在 OpenStack 容器上写入文件

python - 正则表达式 Python 不工作

bash - 使用最大进程数并行化 Bash 脚本

python - 如何更改使用 Tkinter 完成的文本框的背景颜色和文本颜色?

linux - Bash 命令未在 Apache CGI Shell 中运行

python - 对数组的所有元素进行积分

Python:导航到便携设备目录 (Windows 7)