函数在线程中第二次调用时不工作(Pyttsx模块)

2024-10-01 04:46:52 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:大幅减少代码。在

在Python2.7、windows xp上

这是一个小程序,它使用Pyttsx模块来进行文本到语音转换。在

工作: 说出一个特定的文本字符串。将创建一个新线程(runNewThread())来处理说话部分。在

为了停止说话,我使用一个队列与新线程通信,从而停止Pyttsx引擎。在

这一切如期而至。但是,在停止正在说话的线程并创建一个新线程之后,由于某种原因,引擎根本不说话(在第二个新线程内)。thread函数调用正确,engine = Pyttsx.init()的变量类型正确,其他语句执行正确,只有engine.runAndWait()不工作。为什么?在

编辑:它现在也抛出一个异常Exception in thread sayitthread (most likely raised during interpreter shutdown):

import pyttsx
import threading
from threading import *
import datetime
import os
import sys
import time
from Queue import Queue

queue =   Queue()
pauselocation =  0
wordsToSay = ''
play = 0 

#CREATED NEW THREAD
def runNewThread(wordsToSay):    
    e = (queue, wordsToSay)
    t = threading.Thread(target=saythread,args=e,name='sayitthread')
    #t.daemon = True 
    t.start()

#FUNCTION USED AS TARGET FOR NEW THREAD
def saythread(queue , text):
    global pauselocation
    saythread.pause = 0 
    engine = pyttsx.init()
    print ( type(engine) ) 
    saythread.pausequeue1 = False

    def onWord(name, location, length):
        saythread.pausequeue1  = queue.get(False) 
        saythread.pause = location
        if saythread.pausequeue1 == True :
            print 'stopping engine'
            engine.stop() 
            time.sleep(1)

    def engineRun():
        print 'engineRun' , type(engine)
        engine.connect("started-word" , onWord )
        print text
        engine.say(text)
        engine.runAndWait()

    engineRun()
    pauselocation =  saythread.pause
    if saythread.pausequeue1 == False:
        print 'exiting from thread1'
        os._exit(1) 
    print 'after everything'


if __name__ == '__main__':

    wordsToSay = """However little known the feelings or views of such a man may be on his
                    first entering a neighbourhood, this truth is so well fixed in the minds
                    of the surrounding families, that he is considered the rightful property
                    of some one or other of their daughters."""
    runNewThread(wordsToSay) #FIRST THREAD CREATED. THIS WORKS
    time.sleep(5)
    queue.put(True) #SEND IN MESSAGE TO STOP THE ENGINE AND THE THREAD
    time.sleep(5) 
    runNewThread(wordsToSay) #START A NEW THREAD . THE THREAD STARTS. But the ENGINE WON"T WORK

编辑: 这是我的调试器所说的,就在运行第二个线程之前

^{pr2}$

在我看来,即使线程没有活动(t.isAlive()返回false),变量t仍然存在!我想我必须去掉t变量。我试过了。gc.收集(),但没用。在


Tags: oftheimport编辑timequeuedef线程