![](/img/trans.png)
[英]python multiprocessing.Pool Too many files open logging files
[英]python multiprocessing pool and logging
我的應用程序使用multiprocessing.pool並行計算。 現在,我想添加日志記錄功能。 該代碼(不幸的是)需要在Windows上運行。 我在stackoverflow上找到了一篇相關的文章,但是它不起作用。 我想軟件包multiprocessing_logging不支持池。
這是我的代碼:
from multiprocessing_logging import install_mp_handler
def main(): # main function
filename = "XXX" + datetime.datetime.now().strftime('%Y-%m-%d-%H.%M.%S') + ".log"
log_file = os.path.abspath(os.path.join('logs',filename))
multiprocessing.freeze_support() # support multiprocessing
logging.basicConfig(filename=log_file,
filemode='a',
format='%(asctime)s:%(msecs)d (%(processName)s) %(levelname)s %(name)s \t %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logger.info("Start application")
def run(): # main exection
logger.info("Generate outputs for every metrics")
num_cores = multiprocessing.cpu_count()
logger.info("Output Generation execute on " + str(num_cores) + " cores" )
pool = Pool(num_cores, initializer=install_mp_handler )
processed_metrics = pool.map(_generate_outputs, metrics_list)
pool.close()
pool.join()
map(_create_report,processed_metrics)
輔助函數_generate_outputs和_create_report的實現與該問題無關。 當我執行代碼時,正確存儲了由主進程生成的模塊日志,而不是從子進程生成的日志。
[編輯]
我根據注釋更改了代碼。 現在,我的代碼如下所示:
num_cores = multiprocessing.cpu_count()
logger.info("Output Generation execute on " + str(num_cores) + " cores" )
install_mp_handler()
pool = Pool(num_cores, initializer=install_mp_handler )
processed_metrics = pool.map(_generate_outputs, metrics_list)
pool.close()
pool.join()
map(_create_report,processed_metrics)
但是仍然無法捕獲子進程的日志。 程序終止后,我看到一個錯誤:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\multiprocessing_logging.py", line 64, in _receive
record = self.queue.get(timeout=0.2)
File "C:\Python27\lib\multiprocessing\queues.py", line 131, in get
if not self._poll(timeout):
IOError: [Errno 109] The pipe has been ended
Exception in thread mp-handler-0:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Python27\lib\site-packages\multiprocessing_logging.py", line 62, in _receive
while not (self._is_closed and self.queue.empty()):
File "C:\Python27\lib\multiprocessing\queues.py", line 146, in empty
return not self._poll()
IOError: [Errno 109] The pipe has been ended
關鍵要求是程序需要在Windows上運行。
您需要在Pool()
實例化之前調用install_mp_handler()
。
...
install_mp_handler()
pool = Pool(num_cores, initializer=install_mp_handler)
...
最后,一切歸結為將日志記錄通過隊列傳輸到集中式日志處理程序,然后查看multiprocessing_logging.py ,可以清楚地了解該技術。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.