我对python很陌生,可能面临一个非常简单的问题。但是,我无法通过Google找到解决方案,因为我发现的信息表明我的方法应该可以使用。
我要做的就是将数组作为函数的参数传递。
应采用数组的函数:
def load(components):
global status
global numberOfLoadedPremixables
results = []
print('componetnsJson: ', componentsJson, file=sys.stderr)
status = statusConstants.LOADING
for x in range(0, len(components)):
blink(3)
gramm = components[x]['Gramm']
#outcome = load(gramm)
time.sleep(10)
outcome = 3
results.append(outcome)
numberOfLoadedPremixables += 1
status = statusConstants.LOADING_FINISHED
然后我尝试在后台线程上启动此功能:
background_thread = threading.Thread(target=load, args=[1,2,3]) #[1,2,3] only for testing
background_thread.start()
结果,我最终得到了错误:
TypeError:load()带有1个位置参数,但给出了3个
答案 0 :(得分:2)
由于您需要将整个数组作为一个单元传递给函数,因此请将其包装在一个元组中:
background_thread = threading.Thread(target=load, args=([1,2,3],))
(,)
将args
变成单元素元组,并传递给您的函数
之所以发生此问题,是因为python期望args
是一个序列,该序列在传递给函数时会被解包,所以实际上您的函数被调用为:load(1, 2, 3)