我的要求是与多处理并行运行 shell 函数或脚本。目前,我使用以下不使用多重处理的脚本来完成它。此外,当我并行启动 10 个作业时,其中一项作业可能会提前完成,并且必须等待其他 9 个作业完成。我想借助 python 中的多处理来消除这个问题。
i=1
total=`cat details.txt |wc -l`
while [ $i -le $total ]
do
name=`cat details.txt | head -$i | tail -1 | awk '{print $1}'
age=`cat details.txt | head -$i | tail -1 | awk '{print $2}'
./new.sh $name $age &
if (( $i % 10 == 0 )); then wait; fi
done
wait
我想在启用多处理的Python脚本中运行./new.sh $name $age
(考虑到CPU的数量)正如你可以看到$name和$的值每次执行时年龄都会改变。欢迎分享您的想法
最佳答案
首先,您的整个 schel 脚本可以替换为:
awk '{ print $1; print $2; }' details.txt | xargs -d'\n' -n 2 -P 10 ./new.sh
一个简单的Python解决方案是:
from subprocess import check_call
from multiprocessing.dummy import Pool
def call_script(args):
name, age = args # unpack arguments
check_call(["./new.sh", name, age])
def main():
with open('details.txt') as inputfile:
args = [line.split()[:2] for line in inputfile]
pool = Pool(10)
# pool = Pool() would use the number of available processors instead
pool.map(call_script, args)
pool.close()
pool.join()
if __name__ == '__main__':
main()
请注意,这使用 multiprocessing.dummy.Pool
(线程池)来调用外部脚本,在这种情况下,它比进程池更可取,因为所有 call_script
code> 方法的作用是调用脚本并等待其返回。在工作进程而不是工作线程中执行此操作不会提高性能,因为这是基于 IO 的操作。它只会增加进程创建和进程间通信的开销。
关于python - 在 python 中多重处理 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29714832/