Skip to main content
 首页 » 编程设计

python之在 python 中多处理 shell 脚本

2025年05月04日12myhome

我的要求是与多处理并行运行 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 和 $ 的值每次执行时年龄都会改变。请分享您的想法

请您参考如下方法:

首先,您的整个 schell 脚本可以替换为:

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 方法的作用是调用脚本并等待其返回。在工作进程而不是工作线程中执行此操作不会提高性能,因为这是基于 IO 的操作。这只会增加进程创建和进程间通信的开销。