Python dateutil 规则错误
我在下面的示例代码中遇到了以下错误。我不太确定为什么会出现这个错误,因为之前这段代码运行得很好。我使用的是Python 2.7。
AttributeError: 'module' object has no attribute 'allocate_lock'
这里有一个简单的例子,包含了这个问题。
import pandas as pd
import pytz
from datetime import datetime, timedelta
from dateutil import rrule
start = pd.Timestamp('1900-01-01', tz='UTC')
end_base = pd.Timestamp('today', tz='UTC')
end = end_base + timedelta(days=365)
def canonicalize_datetime(dt):
return datetime(dt.year, dt.month, dt.day, tzinfo=pytz.utc)
def get_rules(start, end):
rules = []
start = canonicalize_datetime(start)
end = canonicalize_datetime(end)
weekends = rrule.rrule(
rrule.YEARLY,
byweekday=(rrule.SA, rrule.SU),
cache=True,
dtstart=start,
until=end
)
rules.append(weekends)
return rules
rules = get_rules(start, end)
完整的错误追踪信息
Traceback (most recent call last):
File "/Users/mac/Documents/test.py", line 48, in <module>
rules = get_rules(start, end)
File "/Users/mac/Documents/test.py", line 42, in get_rules
until=end
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dateutil/rrule.py", line 239, in __init__
super(rrule, self).__init__(cache)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dateutil/rrule.py", line 90, in __init__
self._cache_lock = _thread.allocate_lock()
AttributeError: 'module' object has no attribute 'allocate_lock'
根据dateutil的源代码和用户@PatrickCollins的说法,可以通过以下方式重现这个问题:
import _thread
_thread.allocate_lock()
2 个回答
1
在使用Anaconda Python运行Caffe的时候遇到了这个错误;评论里的说法帮我解决了这个问题。
pip install --upgrade python-dateutil
Collecting python-dateutil
Downloading python_dateutil-2.6.0-py2.py3-none-any.whl (194kB)
100% |████████████████████████████████| 194kB 484kB/s
Requirement already up-to-date: six>=1.5 in /home/alex/anaconda3/lib/python3.6/site-packages (from python-dateutil)
Installing collected packages: python-dateutil
Found existing installation: python-dateutil 1.5
Uninstalling python-dateutil-1.5:
Successfully uninstalled python-dateutil-1.5
Successfully installed python-dateutil-2.6.0
1
经过进一步调查,发现问题出在 pip
安装了错误的版本。通过安装 datetuil-1.5 可以解决这个问题。
python-dateutil-2.0.tar.gz (适用于 Python 3.0 及以上版本)
python-dateutil-1.5.tar.gz (适用于 Python 3.0 以下版本)
不过,这可能会引发更多问题,因为有些人在使用 Python 2.7 时,版本 2.2 的 dateutil 却能正常工作。