简体   繁体   English

通过线程将args传递给函数

[英]Passing args to a function through a Thread

I am trying to pass two variable to a function via Thread as below: 我试图通过线程将两个变量传递给函数,如下所示:

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()

But somehow I keep getting the error below: 但是以某种方式我不断收到以下错误:

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)

Do you guys know how to fix this? 你们知道如何解决这个问题吗? How I am supposed to pass those variables correctly? 我应该如何正确传递这些变量?

You need to pass the function to the Thread , not call the function. 您需要将函数传递Thread ,而不是调用函数。 Just remove the parenthesis at the end of play() . 只需在play()末尾删除括号即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM