我在这个问题上做了一些探索,似乎没有一个非常明确的答案。我目前正在做一个项目,用户点击一个按钮,一旦他点击了,我就调用一个python函数,reply()
,这个函数启动两个不同的线程,a
(代表音频)和r
(代表例程)。这两个线程应该一起工作,基本上指向讲述者所说的基于地图的方向:你知道吗
def reply(index, path2, path3):
a = threading.Thread(target=playaudio(path3))
r = threading.Thread(target=routine(path2))
r.start()
a.start()
我想知道是否有一种方法可以访问函数并在用户单击停止按钮时停止playaudio
和routine
函数的线程,这样如果用户不想再看到它,他所需要做的就是停止演示。这两个功能设置如下:
# play audio function starts here:
def playaudio(path):
try:
subprocess.Popen(["mpg123", path])
except Exception as ex:
tkMessageBox.showinfo('Error', 'An error occurred. ' + str(ex))
# routine function starts here
# routine controls the servo module
def routine(path):
with open(path, 'rb') as f:
reader = csv.reader(f)
settings = list(reader)
print(settings)
i = 1
while i < (len(settings) - 1):
try:
setall(int(settings[i][1]), int(settings[i][2]), int(settings[i][3]), int(settings[i][4]))
delay = float(settings[i+1][0]) - float(settings[i][0]) - 0.015 #includes processing time
time.sleep(delay)
i += 1
except Exception as ex:
pass
setall(int(settings[i][1]), int(settings[i][2]), int(settings[i][3]), int(settings[i][4]))
这些将由主屏幕上的Tkinter.Button
元素启动,并将播放音频和控制伺服模块。你知道吗
button = Tkinter.Button(window, text='Audio 4', command=lambda: reply(1, 'path/to/excel/file.csv', '/path/to/audio/file.mp3'))
button.config(width="30", height="5")
button.place(x=490, y=40)
对于stopping函数,我认为添加另一个Tkinter
button元素是一个解决方案,但是使用一个不同的函数,每当用户单击它时就退出subprocess
。你知道吗
stop_button = Tkinter.Button(window, text='Stop Audio', command=lambda: stop())
stop_button.config(width="30", height="5")
stop_button.place(x=490, y=360)
对于实际的stop()
函数,我尝试了一些方法,例如stop()
和destroy()
,但是音频或伺服继续运行,或者实际程序关闭。你知道吗
所以我的问题是,我应该怎么做?我真的很感激任何反馈在这个问题上。你知道吗
你查过Queue module了吗?您可以使用它向线程发送消息。你知道吗
因此,假设您有线程函数可以访问的
q
(一个Queue
实例),那么routine()
线程函数可以如下所示:在
playaudio()
函数中,您希望保留所创建的Popen
对象,并使用'terminate()方法结束进程。请查看subprocess文档以获取有关如何执行此操作的更多信息。你知道吗然后,当用户单击“停止”按钮时,您可以向队列发布消息:
另一方面,我们也来看看多进程模块。Python的GIL阻止了线程的正常执行,而multiprocess能够绕过这一点并利用多核。你知道吗
相关问题 更多 >
编程相关推荐