将字典传递给Python中的线程函数

时间:2014-03-20 19:10:38

标签: python multithreading dictionary

所以,我有一个函数explain(item),它接受1个参数。此参数旨在成为具有8-9个键的字典。当我打电话给explain(item)时,一切都很好。但是当我打电话时(物品是同一个变量)

threads.append(threading.Thread(target = explain, args=(item)))
threads[i].start()
threads[i].join()

我收到这样的错误:

Exception in thread Thread-72:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
TypeError: explain() takes exactly 1 argument (10 given)

我做错了什么?

1 个答案:

答案 0 :(得分:12)

您似乎打算将args参数的单项元组传递给threading.Thread(),但使用args=(item)相当于args=item。您需要添加逗号来创建元组,因此它将是args=(item,)

threads.append(threading.Thread(target = explain, args=(item,))).

如果没有尾随逗号,则括号只是一种分组表达式的方法,例如:

>>> (100)  # this is just the value 100
100
>>> (100,) # this is a one-element tuple that contains 100
(100,)