您的位置:首页 > 编程语言 > Python开发

使用Python处理地理数据文件-多进程处理类

2016-05-14 20:32 603 查看
最近在研究使用ArcGIS制作地图,ArcGIS软件本身提供了丰富完备的地图文件处理工具,但是这些工具都需要手工操作,非常耗费时间。幸好ArcGIS还提供了一套Python库(arcpy),可以基于这个库编写脚本进行数据文件批处理。一般在进行批处理的时候,使用多进程处理任务会加快处理速度,所以打算先封装一个多进程处理的基础类,便于后面写具体功能时使用。

思路大致是这样:

先初始化一个任务队列

将待处理的任务方法和参数打包添加到任务队列中

启动一个固定大小的进程池循环从任务队列中领取任务包

拿出任务包中的方法和参数执行任务

开始编写了一版,源码如下:

from multiprocessing import Manager,Pool
import os, logging, timeit, time

class BatchBase(object):

def __init__(self):
'''
Constructor
'''

def __del__(self):
'''
Destructor
'''

##消费者
def __task_consumer(self,q):
while not q.empty():
try:
task = q.get(block=True,timeout=2)

function = task.get('function')
callback = task.get('callback')
args     = task.get('args')
kwargs   = task.get('kwargs')
name     = task.get('name')
pid      = os.getpid()
try:
print '%d start job %s [%s]!\n' % (pid,name,self.getNowTime())
if callback:
callback(function(*args, **kwargs))
else:
function(*args, **kwargs)

print '%d complete job %s success [%s]!\n' % (pid,name,self.getNowTime())
except Exception as ex:
if callback:
callback(ex)
print '%d complete job %s fail [%s]\n' % (pid,name,self.getNowTime())
print ex
finally:
q.task_done()
except Exception as ex:
logging.error(ex)

def getNowTime(self):
return time.strftime("%H:%M:%S",time.localtime(time.time()))

##初始化任务队列
def batch_init(self):
_manager = Manager()
_queue   = _manager.Queue()
return _queue

##加入job
def batch_join(self, q, name, function, callback, *args, **kwargs):
q.put({
'name': name,
'function': function,
'callback': callback,
'args': args,
'kwargs': kwargs
})

##执行任务
def batch_run(self,q,num_consumer):
_start_time = timeit.default_timer()
_pool       = Pool(processes = num_consumer)
print 'pool initialized with %d workers!' % num_consumer
for i in xrange(num_consumer):
_pool.apply_async(self.__task_consumer,args=(q,))
print 'worker %d started' % i

print 'wait for all workers'
_pool.close()
_pool.join()
print 'all jobs are completed!'
print 'Elapsed Time: %s seconds' % (timeit.default_timer() - _start_time)

##测试代码...

调试执行时直接Exception

PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed

查询了一下,这个错误大意是说“不能序列化实例方法”。

详细了解了下,问题出在进程池的apply_async方法上,这个方法传入的参数需要被序列化,而第一个参数是这个类实例的方法,不能被序列化

_pool.apply_async(self.__task_consumer,args=(q,))

这个问题从stackoverflow上找到一种解决办法,Python中有种机制,只要定义类型的时候,实现了__call__函数,这个类型就成为可调用的。所以在BatchBase类中实现__call__,在__call__中再调用__task_consumer,而后在进程池申请使用方法中将self作为参数传入,进程在执行时会通过__call__调用__task_consumer,从而达到“曲线救国”。

改进后的完整代码如下:

# -*- coding:utf-8 -*-
##========================
'''
Created on 2016年5月14日
@author: Jason
'''
from multiprocessing import Manager,Pool
import os, logging, timeit, time

class BatchBase(object):

def __init__(self):
'''
Constructor
'''

def __del__(self):
'''
Destructor
'''

def __call__(self,q):
return self.__task_consumer(q)

##消费者
def __task_consumer(self,q):
while not q.empty():
try:
task = q.get(block=True,timeout=2)

function = task.get('function')
callback = task.get('callback')
args     = task.get('args')
kwargs   = task.get('kwargs')
name     = task.get('name')
pid      = os.getpid()
try:
print '%d start job %s [%s]!\n' % (pid,name,self.getNowTime())
if callback:
callback(function(*args, **kwargs))
else:
function(*args, **kwargs)

print '%d complete job %s success [%s]!\n' % (pid,name,self.getNowTime())
except Exception as ex:
if callback:
callback(ex)
print '%d complete job %s fail [%s]\n' % (pid,name,self.getNowTime())
print ex
finally:
q.task_done()
except Exception as ex:
logging.error(ex)

def getNowTime(self):
return time.strftime("%H:%M:%S",time.localtime(time.time()))

##初始化任务队列
def batch_init(self):
_manager = Manager()
_queue   = _manager.Queue()
return _queue

##加入job
def batch_join(self, q, name, function, callback, *args, **kwargs):
q.put({
'name': name,
'function': function,
'callback': callback,
'args': args,
'kwargs': kwargs
})

##执行任务
def batch_run(self,q,num_consumer):
_start_time = timeit.default_timer()
_pool       = Pool(processes = num_consumer)
print 'pool initialized with %d workers!' % num_consumer
for i in xrange(num_consumer):
_pool.apply_async(self,args=(q,))
print 'worker %d started' % i

print 'wait for all workers'
_pool.close()
_pool.join()
print 'all jobs are completed!'
print 'Elapsed Time: %s seconds' % (timeit.default_timer() - _start_time)

##############for test##############################
def test_task(name):
print 'Run task %s (%s)...' % (name, os.getpid())
start_time = timeit.default_timer()
time.sleep(3)
end_time = timeit.default_timer()
print 'Task %s runs %0.2f seconds.' % (name, (end_time - start_time))

if __name__=='__main__':

#类实例
batch = BatchBase()

#初始化job队列
jobs  = batch.batch_init()

#循环加入job
for i in range(4):
batch.batch_join(jobs, str(i), test_task, None, str(i))

#执行job(使用3个进程)
batch.batch_run(jobs, 3)

print '任务执行完成.'

执行成功!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息