使用命名元组时出现“'module' 没有属性”

"'module' has no attribute" when working with namedtuples

我运行在这里遇到了一些困难,所以我会尽力解释这个问题。

def playGames(jobQueue, ...):
  ....
  nextJob = jobQueue.get()
  ...

def runPool(fens, timesetting, ...):
  ...
  for fen in fens:
    jobQueue.put(Job(gamefen=fen, timecontrol=timesetting))
  ...

if __name__ == '__main__':
  Job = collections.namedtuple('Job', 'gamefen timecontrol')
  ...
  ...
  playGames(jobQueue, ...) # jobQueue is a multiprocess.Queue() object

运行执行此操作后,将抛出以下错误。

"'module' object has no attribute 'Job'"

所以我将 Job = collections... 行移到 if name==main 上方,它起作用了!

但是,在我的 Ubuntu 系统上,没有 Job = collections... 移动的代码编写方式将工作得很好。

所以 Windows7 使用 python2.7.8 它不起作用 Ubuntu14 使用 python2.7.6 它确实有效 Ubuntu14 使用 python3.4.3 它确实有效

我一定是漏掉了什么...

完整的回溯在这里:

Traceback (most recent call last):
  File "c:\Python27\lib\multiprocessing\process.py", line 258, in _bootstrap
    self.run()
  File "c:\Python27\lib\multiprocessing\process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "c:\Users\Andy\Desktop\Github\LucasZinc\Zinc.py", line 338, in play_games
    _job = jobQueue.get()
  File "c:\Python27\lib\multiprocessing\queues.py", line 117, in get
    res = self._recv()
AttributeError: 'module' object has no attribute 'Job'

在 Windows 上,多处理的实现对代码施加了额外的约束 - 实际上发生的是为每个进程启动不同的 python 解释器,然后这些新的解释器加载 python code as non-main - 因此,要使用 Job,non-main 进程需要在 if __name__=='__main__' 条件语句之外定义 Job。见下文标题 16.6.3.2 https://docs.python.org/2/library/multiprocessing.html