【问题标题】:'module' object has no attribute '_strptime' with several threads Python“模块”对象没有属性“_strptime”,有多个线程 Python
【发布时间】:2015-11-21 14:39:24
【问题描述】:

我收到此错误'module' object has no attribute '_strptime',但仅当我使用多个线程时。当我只使用一个时,它工作正常。我使用 python 2.7 x64。这里是我调用的简化函数

import datetime
def get_month(time):
    return datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S+0000').strftime("%B").lower()

这是完整的回溯:

AttributeError: 'module' object has no attribute '_strptime'

Exception in thread Thread-22:
Traceback (most recent call last):
  File "C:\Python27x64\lib\threading.py", line 810, in __bootstrap_inner
    self.run()
  File "C:\Python27x64\lib\threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "C:\file.py", line 81, in main
    month=get_month(eventtime)
  File "C:\file.py", line 62, in get_month
    return datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S+0000').strftime("%B").lower()
AttributeError: 'module' object has no attribute '_strptime'

【问题讨论】:

  • 完整的回溯是什么?

标签: python multithreading python-2.7 datetime time


【解决方案1】:

我可以确认该问题与多线程有关,当我将datetime.datetime.strptimeThreadPool 模块结合使用时,偶尔会发生这种情况。

我可以通过导入“缺失”模块在我的脚本中解决此问题,如下所示:

import _strptime

【讨论】:

  • 这对我有帮助。谁能解释为什么?为什么会自发出现此错误?
【解决方案2】:

邮件列表消息“threading bug in strptime”中描述了该问题。

datetime.strptime 与 Python 2 的 threading 模块有问题。 似乎建议的解决方法是在启动任何线程之前调用strptime = datetime.datetime.strptime

【讨论】:

  • 这也适用于我在 Python 2.7.17 上一个简单的 非线程 脚本。
【解决方案3】:

刚刚遇到了这个确切的问题。这是一个棘手的问题 - 我花了一个小时左右才找到它。我尝试启动 shell 并输入以下代码:

import datetime

print(datetime.datetime.strptime("2015-4-4", "%Y-%m-%d"))

这很好用。然后我在我的工作区的一个空白文件中尝试了它。这给出了您描述的相同错误。我尝试从工作区的命令行运行它。仍然给出了错误。然后我从我的工作区启动了 shell。这次它在shell环境中给出了错误。事实证明,除了我所在的目录之外的任何目录都可以正常工作。

问题是我的项目是一个 python 日历应用程序,我的主文件名为“calendar.py”。这与某些本地导入冲突,从而产生了奇怪的错误。

在您的情况下,我敢打赌,问题在于您的文件名:“file.py”。把它叫做别的东西,你应该很高兴。

【讨论】:

  • 我正在使用 PyqT :\
  • 问题一定是别的原因
  • 我遇到了这个问题。问题是我的python文件被称为time.py,重命名它使它工作。
【解决方案4】:

我在 Windows 机器上测试一个在 Linux 上运行的脚本时遇到了这个问题,我只需在线程顶部添加一个 import 语句就可以修复它。

def multithreadedFunction():
    from datetime import datetime
    # Rest of the function

在修改你的函数以不使用 datetime 模块之前可能值得尝试一下,因为如果它有效,这是一个更快的修复。

【讨论】:

    【解决方案5】:

    使用 datetime.strptime() 方法的线程模块中出现同样的错误。

    https://bugs.python.org/issue7980 中所述,该方法不会以线程安全的方式导入 _strptime.py。

    最后一个 cmets 说:“这是一个仅限 Python 2.7 的错误,它不是安全问题,因此该问题可能会以“wontfix”的形式关闭(因为我们不会在 Python 2 中修复它) 或“已修复”(因为它已在 Python 3 中修复),具体取决于您的观点。”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-21
      • 2013-12-14
      • 2015-03-09
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 2014-01-25
      • 2019-01-21
      相关资源
      最近更新 更多