在利用Python进行系统管理的时候,特别是同时操作多个文件目录,或者远程控制多台主机,并行操作可以节约大量的时间。当被操作对象数目不大时,可以直接利用multiprocessing中的Process动态成生多个进程,10几个还好,但如果是上百个,上千个目标,手动的去限制进程数量却又太过繁琐,这时候进程池Pool发挥作用的时候就到了。
-
#!/usr/bin/env
python
-
#coding=utf-8
-
"""
-
Author: Squall
-
Last modified: 2011-10-18 16:50
-
Filename: pool.py
-
Description: a simple sample for pool class
- """
-
-
from
multiprocessing import Pool -
from
time import sleep
-
def
f(x): -
for i in range(10): -
print ‘%s --- %s ‘ % (i, x) -
sleep(1) -
-
-
def
main(): -
pool = Pool(processes=3) # set the processes max number 3 -
for i in range(11,20): -
result = pool.apply_async(f, (i,)) -
pool.close() -
pool.join() -
if result.successful(): -
print ‘successful‘ -
-
-
if
__name__ == "__main__": -
main()