Python Поток таймера не прерывается с помощью ярлыка на рабочем столе - PullRequest
0 голосов
/ 13 апреля 2020

Когда я запускаю следующий код из терминала и после выхода из окна, используйте либо Ctrl + C, либо Ctrl + Z, чтобы отменить скрипт, скрипт ПОЛНОСТЬЮ завершается. С Ctrl + C я получаю эту ошибку:

Exception ignored in: <module 'threading' from '/usr/lib/python3.6/threading.py'>
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 1294, in _shutdown
    t.join()
  File "/usr/lib/python3.6/threading.py", line 1056, in join
    self._wait_for_tstate_lock()
  File "/usr/lib/python3.6/threading.py", line 1072, in _wait_for_tstate_lock
    elif lock.acquire(block, timeout):
KeyboardInterrupt

Если я использую ссылку на рабочем столе:

#!/usr/bin/env xdg-open

[Desktop Entry]
Type=Application
Name=MyProblem
Exec=/home/USER/myProblem.py
Terminal=false
Name[en_CA]=myProblem

и выхожу из окна, кажется, что поток все еще работает (указано пытаясь выйти из моего рабочего стола и появившееся уведомление о том, что MyProblem занята.)

Код многопоточности не завершается, и я понимаю, что после того, как многопоточность была запущена после периода ожидания, ее трудно завершить. Я просмотрел множество сообщений, в том числе: Python threading.timer - повторять функцию каждые 'n' секунд Python Threading, темы не закрываются

Поскольку это threading.Timer, похоже, нет способа использовать daemon = True.

Я не уверен, как реализовать полное отключение потоков в closeEvent перед выходом из окна. Все остаются в безопасности. Спасибо.

#!/usr/bin/python3
from datetime import datetime, timedelta
from PyQt5.QtWidgets import (QAction, QApplication, QCheckBox, QGridLayout, QMainWindow, QMenuBar, QWidget)
import os; import subprocess; import sys; import threading; import time
class MyProblem(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
########################################
    def closeEvent(self, event):
# what do I place here - thr is a NoneType
        None
########################################
    def recordTimedAudio(self, tL, tfn):
# record audio
        self.rec_args =['arecord', '--device=hw', '-d', str(tL), '-f', 'cd', '-t', 'wav', tfn +'.wav']
        self.rec = subprocess.Popen(self.rec_args, shell=False)
########################################
    def timedRecording(self):
        dateData =['2020-04-13 13:06:00','2020-04-13 13:07:00'] # this should be changed for future dates/times
# My code uses a for loop to create a number of threads, but the end go through a series
        for d in dateData:
# Create Start Time in Seconds
            t = time.strptime(d, '%Y-%m-%d %H:%M:%S')
            t = time.mktime(t)
            thr = threading.Timer(int(t-time.time()), self.recordTimedAudio, ['10','File1']).start() #/27190809/
            print(thr) # This comes back None
            self.timerAction.setEnabled(False)
########################################
    def initUI(self):
        self.setGeometry(5,5,100,100); self.mainWidget = QWidget()
        self.layout = QGridLayout();   self.mainWidget.setLayout(self.layout)
        self.setCentralWidget(self.mainWidget)
# Menu
        self.mainMenu = self.menuBar()
        self.optionsMenu = self.mainMenu.addMenu('Options')
        self.timerAction = QAction('Set Timer', checkable=True)
        self.timerAction.triggered.connect(self.timedRecording)
        self.optionsMenu.addAction(self.timerAction)
        self.show()
########################################
if __name__ =='__main__':
    app = QApplication(sys.argv)
    ex = MyProblem()
    sys.exit(app.exec_())
################################################################################################END

1 Ответ

0 голосов
/ 16 апреля 2020

Мне не удалось остановить поток, и, возможно, поток был излишним для такой проблемы синхронизации. Я создал обходной путь, который может помочь кому-то в будущем. Замените приведенный выше код этими процедурами:

def timedRecording(self):
    dateData =['2020-04-13 13:06:00','2020-04-13 13:07:00'] # this should be changed for future dates/times
    for d in dateData:
# Create Start Time in Seconds
        t = time.strptime(d, '%Y-%m-%d %H:%M:%S')
        t = time.mktime(t)
        self.timerData.append([t, trecLength, urlText, tfilename]) # start time recording length, url, filename
    self.timerData.sort(key = lambda x: x[0]) # /4174941/
    self.treclen = len(self.timerData)
    if self.treclen>0:
        self.rtime.setText('Timer Set')
        self.timerAction.setEnabled(False)
        self.startTRecTimer()
########################################
def recordTimedAudio(self, tL, urlText, tfn):
    self.rec_args =['arecord', '--device=hw', '-d', str(tL), '-f', 'cd', '-t', 'wav', os.path.join(os.path.sep,self.audioDir, tfn +'.wav')]
    self.rec = subprocess.Popen(self.rec_args, shell=False) #https://docs.python.org/2/library/subprocess.html#popen-constructor
# Learning a trick from: https://stackoverflow.com/questions/27190809/
    if self.trecNum < self.treclen-1:
        self.trecNum+=1
        self.startTRecTimer()
########################################
def startTRecTimer(self):
    if time.time() < self.timerData[self.trecNum][0]: # time has not elapsed /415511/
# Start QTimer delay then Start Recording
        delayTime = int(self.timerData[self.trecNum][0]-time.time())*1000 # QTimer uses milliseconds
        self.trecTimer = QTimer()
        self.trecTimer.setSingleShot(True)
        self.trecTimer.timeout.connect(lambda: self.recordTimedAudio(self.timerData[self.trecNum][1], self.timerData[self.trecNum][2], self.timerData[self.trecNum][3]))
        self.trecTimer.start(delayTime)

Также добавьте в initUI:

self.rec = None

И в closeEvent окна:

        if self.rec != None:
            self.rec.terminate() # /16866602/

Так что подпроцесс остановлен.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...