【问题标题】:"'module' has no attribute" when working with namedtuples使用命名元组时“'模块'没有属性”
【发布时间】:2016-08-01 04:47:28
【问题描述】:

我在这里遇到了一些障碍,所以我会尽力解释这个问题。

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...moved 的代码编写方式可以正常工作。

所以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'

【问题讨论】:

  • 请显示完整的错误信息和完整的回溯。
  • 添加了回溯

标签: python collections queue namedtuple


【解决方案1】:

在 Windows 上,多处理的实现对代码施加了额外的限制——实际上发生的情况是为每个进程启动不同的 python 解释器,然后这些新的解释器将 python 代码加载为非主——所以,要使用 Job,非主进程需要在if __name__=='__main__' 条件语句之外定义 Job。请参阅下面的标题 16.6.3.2 https://docs.python.org/2/library/multiprocessing.html

【讨论】:

  • 优秀。这个理由很有意义。很高兴看到它的来源。谢谢你的时间!时间一到,我会接受答案。
猜你喜欢
  • 2014-11-02
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 2019-04-18
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多