2017-08-13 83 views
0

我正在從線程調用函數,只要函數開始運行,線程就會停止工作,直到函數完成執行並且函數執行後該程序停止。從線程調用函數並讓原始線程在後臺運行

class listen(threading.Thread): 

    def __init__(self): 
     threading.Thread.__init__(self) 
     self.playmusicobject = playmusic() 
     self.objectspeak = speak() 
     self.apiobject = googleAPI() 

    def listening(self): 

     self.r = sr.Recognizer() 
     threadLock.acquire() 
     try: 

      with sr.Microphone() as source: 
       print("say something") 
       self.audio = self.r.listen(source) 

     finally: 
      threadLock.release() 

    def checkingaudio(self): 

     threadLock.acquire() 
     try: 
      # a = str(self.r.recognize_google(self.audio)) 
      a = str(self.r.recognize_google(self.audio)) 
      print(a) 
      if a in greetings: 
       self.objectspeak.speaking("I am good how are you?") 

      if a in music: 
       print("playing music") 
       self.playmusicobject.play() 

      if a in stop: 
       print("stopping") 
       self.playmusicobject.b() 

      if a in api: 
       self.apiobject.distance() 
     finally: 
      threadLock.release() 

class playmusic: 

    def play(self): 
     playsound.playsound("playthisfile") 

if __name__ == "__main__": 
    while 1: 
     d = listen() 
     t1 = threading.Thread(target=d.listening) 
     t1.start() 
     t2 = threading.Thread(target=d.checkingaudio) 
     t2.start() 

無論何時我在playmusic中調用play函數,線程都會停止,並且在play函數執行後程序停止。無論如何,該函數發揮作用或事實上任何其他函數運行函數CheckingAudio線程調用,不會停止2原始線程。我試圖運行播放函數作爲自己的線程,但沒有處理這樣做,它只是給了我一個錯誤,說無法啓動線程T3,途中被調用函數作爲一個線程(這可能是錯誤的)

 if a in music: 
      print("playing music") 
      t3 = threading.Thread(target=self.playmusicobject.play) 
      t3.start() 

我試圖創造playmusic類runplaythread功能但仍然給我錯誤無法啓動線程。

回答

0

不確定它會解決您的問題,但您最後一個線程的目標是錯誤的,您正在使用self而不是d來調用您的實例listen

這是你的代碼糾正,以替換上下文

if a in music: 
     print("playing music") 
     t3 = threading.Thread(target=d.playmusicobject.play) 
     t3.start() 

注:評論可能早就確定,但沒有足夠的代表。

編輯:重新使用OP的上下文代碼現在明確提到。 (雖然這是顯而易見的)

編輯2:你在哪裏打電話給你的第三個線程不清楚,但似乎不好,見評論。

+0

你真的從我的問題中拿走了代碼並將其作爲答案介紹了,我之所以使用'self.playmusicobject.play'是因爲play函數在不同的類中。注意:投票可能是最好的,但對不起沒有足夠的代表 –

+0

正如在我的回答中所說的,你在代碼中使用'self'而不是實例名'd'。我糾正了這一情況,並重新使用了您的代碼進行上下文。我還提到我無法評論你的答案,並且它會比單獨的答案更好。我會編輯它以便更明確,但請注意細節。 – FabienP

+0

此外,我不確定從類中啓動線程(如果這是您的建議)是一個好主意,因爲您在第一種方法中使用了「threadLock」。 – FabienP