簡體   English   中英

通過線程將args傳遞給函數

[英]Passing args to a function through a 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)

你們知道如何解決這個問題嗎? 我應該如何正確傳遞這些變量?

您需要將函數傳遞Thread ,而不是調用函數。 只需在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