使用Python的multiprocess模块运行多个Gearman进程

2 投票
1 回答
918 浏览
提问于 2025-04-17 08:50

我想用Python的多进程模块来同时运行多个gearman工作进程,但看起来这些进程是一个接一个地执行的。如果我在几个终端中分别运行worker.py程序,那就没问题。但我想减少手动在这么多个终端中指定worker.py的麻烦。有没有什么其他的方法可以做到这一点呢?

import sys , os , simplejson
from fabric import *
from fabric.api import *
import gearman
from gearman import GearmanWorker
from multiprocessing import Pool


##--Global Variables--##
#Spawing minimun 5 worker threads for Gearman



#executing the Job. gmJob consist of dict[host , cmd , pass] 
def exe_job(gmWorker , gmJob ):
 print " the worker process is " , os.getpid()
 d = simplejson.loads(gmJob.data)
 env.host_string = d['host'] 
 env.password = d['pass']  #will store the password .
 cmds = d['cmd']
 print cmds
 for i in cmds:
  sudo (i )  # using fabric functions to ssh into system  
 return "job sucessfull"

def start_exe():
 #woker node id to be specified in here
 gm_worker = gearman.GearmanWorker(['localhost:4730'])
 #gm_worker.set_client_id('client1')
 gm_worker.register_task('exe_job',exe_job)
 gm_worker.work()


if __name__ == '__main__':
 p = Pool(5)
 result = p.apply_async(start_exe)
 print result.get()

1 个回答

1

我也找不到这个问题的答案,所以我自己研究了一下,发现其实你需要用一个队列来跟踪哪些进程是打开的,哪些是关闭的(在gearman工作者的情况下,如果出错的话)。总之,我把这个功能做成了一个模块,并把它发布到了pypi上。这个模块还在不断完善中,但我会尽量在接下来的一两天内添加一些文档和示例:

我还包含了客户端和工作者类,它们通过json进行通信(我提到这个是因为你的例子似乎也在用json)。

告诉我你的想法。如果能有更多人帮我看看,找找bug或者告诉我代码里哪里做得太疯狂了,那就太好了。

撰写回答