“Python多处理”;can';t pickle“;使用日志记录时
我正在使用multiprocessing.Pool并行化我为模拟(D&D 5e中的战斗)编写的一些Python代码。但是,我遇到了这个错误:“Python多处理”;can';t pickle“;使用日志记录时,python,logging,multiprocessing,python-multiprocessing,python-logging,Python,Logging,Multiprocessing,Python Multiprocessing,Python Logging,我正在使用multiprocessing.Pool并行化我为模拟(D&D 5e中的战斗)编写的一些Python代码。但是,我遇到了这个错误:无法pickle\u thread.RLock对象。我做了一些研究,问题似乎是我的模拟使用了具有记录器的对象(来自日志记录模块)。我仍然希望支持模拟的单个进程运行的日志记录(这样人们就可以进行调试/检查输出),但对我来说,多个进程运行的日志记录支持就不那么重要了,因为一旦用户知道模拟正常工作,他们通常就不需要逐个播放了。我如何重构代码以使日志记录不再是问题(
无法pickle\u thread.RLock对象
。我做了一些研究,问题似乎是我的模拟使用了具有记录器的对象(来自日志记录模块)。我仍然希望支持模拟的单个进程运行的日志记录(这样人们就可以进行调试/检查输出),但对我来说,多个进程运行的日志记录支持就不那么重要了,因为一旦用户知道模拟正常工作,他们通常就不需要逐个播放了。我如何重构代码以使日志记录不再是问题(当存在多个进程时禁用日志记录,以多进程接受的方式实现日志记录,或其他方式)
我的模拟类中的一些代码:
def process_run(self, num): # pylint: disable=unused-argument
"""
The method given to an individual process to do work. Run only once per process so we don't need to reset anything
:param num: which iteration of the loop am I
:return:
"""
self._encounter.run()
return self._encounter.get_stats()
def mp_run(self, n=1000, p=None):
"""
Run the Encounter n times (using multiprocessing), then print the results
:param n: number of times to run the encounter
:param p: number of processes to use. If None, use max number of processes
:return: aggregate stats
"""
if p:
pool = Pool(p) # use user-specified number of processes
else:
pool = Pool() # use max number of processes as user didn't specify
for result in pool.imap_unordered(self.process_run, range(n)):
self.update_stats(result)
pool.close()
pool.join()
self.calculate_aggregate_stats(n)
self.print_aggregate_stats()
return self._aggregate_stats
一些使用日志记录的代码(来自Conference类,每个模拟都有一个实例):
如果您需要更多的代码示例,请告诉我
self.get_logger().info("Round %d", self.get_round())
unconscious = [comb.get_name() for comb in self.get_combatants() if comb.has_condition("unconscious")]
if unconscious:
self.get_logger().info("Unconscious: %s", str(unconscious))
dead = [comb.get_name() for comb in self.get_combatants() if comb.has_condition("dead")]
if dead:
self.get_logger().info("Dead: %s", str(dead))