在python中访问函数和停止线程介质和伺服子进程

2024-05-29 04:38:30 发布

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

我在这个问题上做了一些探索,似乎没有一个非常明确的答案。我目前正在做一个项目,用户点击一个按钮,一旦他点击了,我就调用一个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()

我想知道是否有一种方法可以访问函数并在用户单击停止按钮时停止playaudioroutine函数的线程,这样如果用户不想再看到它,他所需要做的就是停止演示。这两个功能设置如下:

# 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函数,我认为添加另一个Tkinterbutton元素是一个解决方案,但是使用一个不同的函数,每当用户单击它时就退出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(),但是音频或伺服继续运行,或者实际程序关闭。你知道吗

所以我的问题是,我应该怎么做?我真的很感激任何反馈在这个问题上。你知道吗


Tags: path函数用户settingsdefasbutton音频
1条回答
网友
1楼 · 发布于 2024-05-29 04:38:30

你查过Queue module了吗?您可以使用它向线程发送消息。你知道吗

因此,假设您有线程函数可以访问的q(一个Queue实例),那么routine()线程函数可以如下所示:

def routine(path):

    # skip some stuff...

    while i < (len(settings) - 1):
        if not q.empty():
            message = q.get()
            if message == 'stop':
                break

        # rest of your function

playaudio()函数中,您希望保留所创建的Popen对象,并使用'terminate()方法结束进程。请查看subprocess文档以获取有关如何执行此操作的更多信息。你知道吗

然后,当用户单击“停止”按钮时,您可以向队列发布消息:

def stop():
    q.put('stop')

另一方面,我们也来看看多进程模块。Python的GIL阻止了线程的正常执行,而multiprocess能够绕过这一点并利用多核。你知道吗

相关问题 更多 >

    热门问题