所以,我有一个带有 1 个参数的函数 explain(item)。此参数旨在成为具有 8-9 个键的字典。当我调用 explain(item)
时一切正常。但是当我调用时(items 是同一个变量)
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)
我做错了什么?
最佳答案
看起来您打算将单项元组作为 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,)
关于python - 将字典传递给 Python 中的线程函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22542866/