python多线程给出类型错误

时间:2013-12-19 15:23:31

标签: python multithreading typeerror python-multithreading

这是我的一段代码,因为我正在尝试使用多线程

unipidA = ['list of data IDs with 6 characters each']

import threading;
from time import ctime()

def parse_data('give_data_id'):
    < code to parse data from server and
      each data ID has unique 6 character string e.g 'Q9NR22', 'Q86WR7' etc>

    print 'The data ', data_id, ' has been parsed'


def main():
    print 'Data Parsing Started at ', ctime()
    threads = []
    mylen = range(len(unipidA))
    for i in mylen:
        print unipidA[i]
        t = threading.Thread(target = parse_data ,args=(unipidA[i]))
        threads.append(t)

    for i in mylen:
        threads[i].start()

    for i in mylen:
        threads[i].join()

    print 'all done at:', ctime()

当我将其作为:

运行时
>>> main() <Enter>

它出现以下错误

>>> File "/usr/lib/python2.7/threading.py", line 504, in run
       self.__target(*self.__args, **self.__kwargs)
    TypeError: parse_data() takes exactly 1 argument (6 given)

有人可以解释一下,因为代码在多线程中非常原始,但我仍然无法追踪问题。谢谢!

1 个答案:

答案 0 :(得分:2)

args=(unipidA[i])

这不是你的想法。括号不会使它成为元组,在这种情况下,它只相当于args=unipidA[i]。我想在这种情况下,它是一个长度为6的字符串。

要创建一个可以作为args参数正确传递的元组,请添加一个尾随逗号:

t = threading.Thread(target = parse_data ,args=(unipidA[i],))

另见:

>>> (1)
1
>>> (1,)
(1,)