4

I have a python function that works okay in "normal" mode but throws an error when I run it in a threaded function.

Function

def is_valid_date(date_value, is_mandatory): 
    '''validate a date value. Return True if its a valid date
    http://stackoverflow.com/questions/2216250/how-can-i-validate-a-date-in-python-3-x
    '''
    try:
        if is_mandatory == True:
            if len(date_value) != 8:
                return False
            y = date_value[0:4]
            m = date_value[4:6]
            d = date_value[6:8]
            date_value = d + "/" + m + "/" + y
            date_value = time.strptime(date_value, '%d/%m/%Y') 
            return True
        else:
            if len(date_value) > 0:
                if len(date_value) != 8:
                    return False
                y = date_value[0:4]
                m = date_value[4:6]
                d = date_value[6:8]
                date_value = d + "/" + m + "/" + y
                date_value = time.strptime(date_value, '%d/%m/%Y') 
                return True
            else:
                return True     
    except ValueError:
        return False  

Error:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.2/threading.py", line 740, in _bootstrap_inner
    self.run()
  File "/home/lukik/apps/myapp/data_file/validate.py", line 97, in run
    is_valid, text_returned = is_valid_data_type(self.myText, dt_columns[colCounter].data_type, dt_columns[colCounter].mandatory)
  File "/home/lukik/apps/myapp/helper.py", line 27, in is_valid_data_type
    if is_valid_date(text_to_check, is_mandatory) != True:
  File "/home/lukik/apps/myapp/helper.py", line 91, in is_valid_date
    date_value = time.strptime(date_value, '%d/%m/%Y')
AttributeError: _strptime_time

Is it the date function that has an error or is this a "race condition" in my queuing and threading function?

4

1 回答 1

5

time.strptime()显然,在 python 2.6 到 3.2 中以线程模式运行函数时存在错误。我找到了一个指向bugs.python.org的SO 链接,该链接指示了该错误。

根据 SO 链接上的@interjay 的技巧,您需要在初始化线程之前调用 time.strptime() 。到目前为止,它对我有用。不知道是否有人有更好的解决方案,因为这感觉更像是一种解决方法而不是解决方案。

于 2013-07-30T20:28:56.680 回答