通过线程将args传递给函数

时间:2014-12-15 17:45:40

标签: python multithreading args

我试图通过Thread将两个变量传递给一个函数,如下所示:

from os import system
from sys import exc_info
from threading import Thread
import time


def play(file, priority):

    try:
        if priority == 0:
            system('ps aux | grep mpg321 | grep -v "grep mpg321" | awk \'{print $2}\' | xargs kill -9')

        statement = 'sudo -u pi mpg321 -g 1 -q -a bluetooth sound/' + file
        system(statement)

    except:
        print('There was an error playing the sound - ' + str(exc_info()[0]))

    finally:
        pass

t1Sound = 'presence.mp3'
t2Sound = 'ultra.mp3'

t1 = Thread(target=play(), args=(t1Sound, 0))
t2 = Thread(target=play(), args=(t2Sound, 1))

t1.start()
time.sleep(2)
t2.start()

但不知怎的,我不断收到以下错误:

sudo python test.py
Traceback (most recent call last):
  File "test.py", line 25, in <module>
    t1 = Thread(target=play(), args=(t1Sound, 0))
TypeError: play() takes exactly 2 arguments (0 given)

你们知道如何解决这个问题吗?我应该如何正确传递这些变量?

1 个答案:

答案 0 :(得分:2)

您需要函数传递给Thread,而不是调用该函数。只需删除play()末尾的括号。

t1 = Thread(target=play, args=(t1Sound, 0))
t2 = Thread(target=play, args=(t2Sound, 1))