이 주제에 대해 몇 가지 검색을 해왔지만 내 질문에 대한 명확한 답변이없는 것 같습니다. 나는 현재 사용자가 버튼을 클릭하고 그가 파이썬 함수를 호출 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)
중지 기능의 경우 다른 Tkinter
버튼 요소 를 추가하는 것이 해결책이 될 것이라고 생각 했지만 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()
오디오 또는 서보가 계속 실행되거나 실제 프로그램이 종료됩니다.
그래서 내 질문은, 내가 다르게 무엇을해야 하는가? 이 문제에 대한 의견을 보내 주시면 감사하겠습니다.
큐 모듈 을 살펴 보셨습니까 ? 스레드에 메시지를 보낼 수 있습니다.
따라서 스레드 함수에 액세스 할 수있는 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
사용자가 만든 객체와 프로세스를 종료하기 위해 '종료 () 메서드를 사용합니다. 이를 수행하는 방법에 대한 자세한 정보 는 하위 프로세스 문서를 참조하십시오.
그런 다음 사용자가 "중지"버튼을 클릭하면 큐에 메시지를 게시 할 수 있습니다.
def stop():
q.put('stop')
제쳐두고 다중 프로세스 모듈도 살펴보십시오. Python의 GIL은 스레딩이 제대로 발생하지 않도록 방지하고 다중 프로세스는이를 우회하여 다중 코어를 사용할 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다