Закрытие программы через 5 минут работы

Следующая ситуация: мне нужно каким-то образом, с помощью реестра закрыть программу через 5 минут работы и попросить, например, купить прайм-подписку.

Максимум, что у меня вышло - это реализовать закрытие через определённо кол-во запусков.

import winreg
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow
number, start_program = "", True


def software():
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE") as sub_key:
            try:
                i = 0
                while True:
                    path_value = winreg.EnumKey(sub_key, i)
                    print(f"{path_value}")
                    i += 1
            except OSError:
                print()
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)


def read_key_software():
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run") as sub_key:
            try:
                i = 0
                while True:
                    path_value = winreg.EnumValue(sub_key, i)
                    print(f"{path_value}")
                    i += 1
            except OSError:
                print("")
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)


def matherboard():
    name_board = "BaseBoardProduct"
    n_b = True
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "HARDWARE\\DESCRIPTION\\System\\BIOS") as sub_key:
            try:
                i = 0
                while n_b:
                    path_value = winreg.EnumValue(sub_key, i)
                    if name_board == path_value[0]:
                        print(f"Matherboard: {path_value[1]}")
                        n_b = False
                    else:
                        i += 1
            except OSError:
                print("matherboard not found")
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)
    print("")


def processor():
    name_proc = "ProcessorNameString"
    n_p = True
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0") as sub_key:
            try:
                i = 0
                while n_p:
                    path_value = winreg.EnumValue(sub_key, i)
                    if name_proc == path_value[0]:
                        print(f"Proseccor: {path_value[1]}")
                        n_p = False
                    else:
                        i += 1
            except OSError:
                print("processor not found")
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)
    print("")


def SPLab():
    global number, start_program
    path = False
    with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE") as sub_key:
            winreg.CreateKey(sub_key, "SPLab")
    winreg.CloseKey(hkey)
    with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE\\SPLab", 0, winreg.KEY_READ) as sub_key:
            try:
                num = winreg.EnumValue(sub_key, 0)
                path = True
                start = num[1]
                if int(start) >= 10:
                    start_program = False
            except OSError:
                path = False
        winreg.CloseKey(sub_key)
        with winreg.OpenKey(hkey, "SOFTWARE\\SPLab", 0, winreg.KEY_WRITE) as sub_key:
            if path:
                start = int(start) + 1
            else:
                start = "1"
            winreg.SetValueEx(sub_key, "NamberOfStarts", 0, winreg.REG_SZ, str(start))
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)
    number = start
    print("")


class mainWin(QMainWindow):
    def __init__(self):
        super(mainWin, self).__init__()
        self.setWindowTitle("Program")

        if start_program:
            self.setGeometry(1000, 300, 580, 270)
            self.setStyleSheet("background : lightyellow;")
            self.b1 = QtWidgets.QPushButton(self)
            self.b1.setGeometry(20, 20, 250, 70)
            self.b1.setStyleSheet("background : lightgreen; font-size : 20px")
            self.b1.setText("software")
            self.b1.clicked.connect(software)
            self.b2 = QtWidgets.QPushButton(self)
            self.b2.setGeometry(300, 20, 250, 70)
            self.b2.setStyleSheet("background : lightgreen; font-size : 20px")
            self.b2.setText("read_key_software")
            self.b2.clicked.connect(read_key_software)
            self.b3 = QtWidgets.QPushButton(self)
            self.b3.setGeometry(20, 120, 250, 70)
            self.b3.setStyleSheet("background : lightgreen; font-size : 20px")
            self.b3.setText("matherboard")
            self.b3.clicked.connect(matherboard)
            self.b4 = QtWidgets.QPushButton(self)
            self.b4.setGeometry(300, 120, 250, 70)
            self.b4.setStyleSheet("background : lightgreen; font-size : 20px")
            self.b4.setText("processor")
            self.b4.clicked.connect(processor)
            self.l5 = QtWidgets.QLabel(self)
            self.l5.setGeometry(20, 210, 250, 50)
            self.l5.setText(f"Number of starts: {number}")
            self.l5.setStyleSheet("font-size : 20px")
        else:
            self.setGeometry(800, 400, 850, 300)
            self.setStyleSheet("background : white;")
            self.l1 = QtWidgets.QLabel(self)
            self.l1.setGeometry(25, 100, 1000, 70)
            self.l1.setText("Buy the full version of the program!")
            self.l1.setStyleSheet("font-size : 50px")


if __name__ == "__main__":
    SPLab()
    app = QApplication(sys.argv)
    mwin = mainWin()
    mwin.show()
    print("")
    sys.exit(app.exec_())

Ответы (1 шт):

Автор решения: S. Nick

Класс QTimer предоставляет повторяющиеся и однократные таймеры.

Больше https://doc.qt.io/qt-5/qtimer.html

В моем примере сработает через 5 секунд, установите нужное вам время.

import winreg
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow

from PyQt5.Qt import *                                # +++

number, start_program = "", True


def software():
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE") as sub_key:
            try:
                i = 0
                while True:
                    path_value = winreg.EnumKey(sub_key, i)
                    print(f"{i} - {path_value}")
                    i += 1
            except OSError as e:
                print(f'OSError: ------------- {e}')
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)


def read_key_software():
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run") as sub_key:
            try:
                i = 0
                while True:
                    path_value = winreg.EnumValue(sub_key, i)
                    print(f"{path_value}")
                    i += 1
            except OSError:
                print("")
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)


def matherboard():
    name_board = "BaseBoardProduct"
    n_b = True
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "HARDWARE\\DESCRIPTION\\System\\BIOS") as sub_key:
            try:
                i = 0
                while n_b:
                    path_value = winreg.EnumValue(sub_key, i)
                    if name_board == path_value[0]:
                        print(f"Matherboard: {path_value[1]}")
                        n_b = False
                    else:
                        i += 1
            except OSError:
                print("matherboard not found")
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)
    print("")


def processor():
    name_proc = "ProcessorNameString"
    n_p = True
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0") as sub_key:
            try:
                i = 0
                while n_p:
                    path_value = winreg.EnumValue(sub_key, i)
                    if name_proc == path_value[0]:
                        print(f"Proseccor: {path_value[1]}")
                        n_p = False
                    else:
                        i += 1
            except OSError:
                print("processor not found")
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)
    print("")


def SPLab():
    global number, start_program
    path = False
    
    with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE") as sub_key:
            winreg.CreateKey(sub_key, "SPLab")
    winreg.CloseKey(hkey)
    
    with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE\\SPLab", 0, winreg.KEY_READ) as sub_key:
            try:
                num = winreg.EnumValue(sub_key, 0)
                path = True
                start = num[1]
                if int(start) >= 10:
                    start_program = False
            except OSError:
                path = False
        winreg.CloseKey(sub_key)
        with winreg.OpenKey(hkey, "SOFTWARE\\SPLab", 0, winreg.KEY_WRITE) as sub_key:
            if path:
                start = int(start) + 1
            else:
                start = "1"
                
            winreg.SetValueEx(sub_key, "NamberOfStarts", 0, winreg.REG_SZ, str(start))
            
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)
    number = start
    print("")


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Program")
        
        self.centralWidget = QWidget(self)                       # +++
        self.setCentralWidget(self.centralWidget)                # +++
        self.grid_layout = QGridLayout(self.centralWidget)       # +++

        if start_program:
            self.b1 = QtWidgets.QPushButton(self)
            self.grid_layout.addWidget(self.b1, 1, 1)            # +++
            self.b1.setText("software")
            self.b1.clicked.connect(software)
            
            self.b2 = QtWidgets.QPushButton(self)
            self.grid_layout.addWidget(self.b2, 1, 2)            # +++
            self.b2.setText("read_key_software")
            self.b2.clicked.connect(read_key_software)
            
            self.b3 = QtWidgets.QPushButton(self)
            self.grid_layout.addWidget(self.b3, 2, 1)            # +++
            self.b3.setText("matherboard")
            self.b3.clicked.connect(matherboard)
            
            self.b4 = QtWidgets.QPushButton(self)
            self.grid_layout.addWidget(self.b4, 2, 2)            # +++
            self.b4.setText("processor")
            self.b4.clicked.connect(processor)
            
            self.l5 = QtWidgets.QLabel(self)
            self.l5.setObjectName('l5')
            self.grid_layout.addWidget(self.l5, 3, 1, 1, 2)       # +++
            self.l5.setText(f"Number of starts: {number}")

# !!! vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv            
            QtCore.QTimer.singleShot(1000 * 5,     self.end_program)
#                                    1000 * 60 * 5  --> пять минут           
        else:
            self.end_program()
        
    def end_program(self):
        self.l1 = QtWidgets.QLabel(self)
        self.l1.setObjectName('l1')
        self.l1.setText("Buy the full version of the program!")
        
        self.setCentralWidget(self.l1)

#  здесь, если вам надо, установить -------------------------->   '10'
#                                                                 vvvv
#  ...                                                            vvvv
#  winreg.SetValueEx(sub_key, "NamberOfStarts", 0, winreg.REG_SZ, '10')        

# !!! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Stylesheet = '''
QWidget {
    background : lightyellow;
}
QPushButton {
    background : lightgreen;  
    font-size : 20px;
    width: 250px;
    height: 70px;
}
#l1 {
    font-size : 50px;
}
#l5 {
    font-size : 20px;
}
'''



if __name__ == "__main__":
    SPLab()
    app = QApplication(sys.argv)
    app.setStyleSheet(Stylesheet)
    mwin = MainWindow()
    mwin.show()
    print("start")
    sys.exit(app.exec_())

введите сюда описание изображения

введите сюда описание изображения


Update:

я заметил, что после перезапуска программа опять работает. Можно как-то привязать время к реестру чтобы второй раз уже нельзя было запустить?

не очень понимаю куда вставить эту строчку, можете объяснить?

import winreg
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow

from PyQt5.Qt import *                                

number, start_program = "", True


def software():
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE") as sub_key:
            try:
                i = 0
                while True:
                    path_value = winreg.EnumKey(sub_key, i)
                    print(f"{i} - {path_value}")
                    i += 1
            except OSError as e:
                print(f'OSError: ------------- {e}')
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)


def read_key_software():
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run") as sub_key:
            try:
                i = 0
                while True:
                    path_value = winreg.EnumValue(sub_key, i)
                    print(f"{path_value}")
                    i += 1
            except OSError:
                print("")
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)


def matherboard():
    name_board = "BaseBoardProduct"
    n_b = True
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "HARDWARE\\DESCRIPTION\\System\\BIOS") as sub_key:
            try:
                i = 0
                while n_b:
                    path_value = winreg.EnumValue(sub_key, i)
                    if name_board == path_value[0]:
                        print(f"Matherboard: {path_value[1]}")
                        n_b = False
                    else:
                        i += 1
            except OSError:
                print("matherboard not found")
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)
    print("")


def processor():
    name_proc = "ProcessorNameString"
    n_p = True
    with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as hkey:
        with winreg.OpenKey(hkey, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0") as sub_key:
            try:
                i = 0
                while n_p:
                    path_value = winreg.EnumValue(sub_key, i)
                    if name_proc == path_value[0]:
                        print(f"Proseccor: {path_value[1]}")
                        n_p = False
                    else:
                        i += 1
            except OSError:
                print("processor not found")
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)
    print("")


def SPLab(blocking=False):                                          # +++ blocking=False
    global number, start_program
    path = False
    
    with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE") as sub_key:
            winreg.CreateKey(sub_key, "SPLab")
    winreg.CloseKey(hkey)
    
    with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as hkey:
        with winreg.OpenKey(hkey, "SOFTWARE\\SPLab", 0, winreg.KEY_READ) as sub_key:
            try:
                num = winreg.EnumValue(sub_key, 0)
                path = True
                start = num[1]
                if int(start) >= 10:
                    start_program = False
            except OSError:
                path = False
        winreg.CloseKey(sub_key)
        with winreg.OpenKey(hkey, "SOFTWARE\\SPLab", 0, winreg.KEY_WRITE) as sub_key:
            if path:
                start = int(start) + 1
            else:
                start = "1"

# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv            
            if blocking: 
                winreg.SetValueEx(sub_key, "NamberOfStarts", 0, winreg.REG_SZ, '10')
            else:
                winreg.SetValueEx(sub_key, "NamberOfStarts", 0, winreg.REG_SZ, str(start))
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^           
            
        winreg.CloseKey(sub_key)
    winreg.CloseKey(hkey)
    number = start
    print("")


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Program")
        
        self.centralWidget = QWidget(self)                   
        self.setCentralWidget(self.centralWidget)            
        self.grid_layout = QGridLayout(self.centralWidget)   

        if start_program:
            self.b1 = QtWidgets.QPushButton(self)
            self.grid_layout.addWidget(self.b1, 1, 1)        
            self.b1.setText("software")
            self.b1.clicked.connect(software)
            
            self.b2 = QtWidgets.QPushButton(self)
            self.grid_layout.addWidget(self.b2, 1, 2)       
            self.b2.setText("read_key_software")
            self.b2.clicked.connect(read_key_software)
            
            self.b3 = QtWidgets.QPushButton(self)
            self.grid_layout.addWidget(self.b3, 2, 1)      
            self.b3.setText("matherboard")
            self.b3.clicked.connect(matherboard)
            
            self.b4 = QtWidgets.QPushButton(self)
            self.grid_layout.addWidget(self.b4, 2, 2)      
            self.b4.setText("processor")
            self.b4.clicked.connect(processor)
            
            self.l5 = QtWidgets.QLabel(self)
            self.l5.setObjectName('l5')
            self.grid_layout.addWidget(self.l5, 3, 1, 1, 2)  
            self.l5.setText(f"Number of starts: {number}")

          
            QtCore.QTimer.singleShot(1000 * 5,     self.end_program)
#                                    1000 * 60 * 5  --> пять минут           
        else:
            self.end_program()
        
    def end_program(self):
        self.l1 = QtWidgets.QLabel(self)
        self.l1.setObjectName('l1')
        self.l1.setText("Buy the full version of the program!")
        
        self.setCentralWidget(self.l1)

# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv            
       
        SPLab(blocking=True)                               # !!! <---- 

# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Stylesheet = '''
QWidget {
    background : lightyellow;
}
QPushButton {
    background : lightgreen;  
    font-size : 20px;
    width: 250px;
    height: 70px;
}
#l1 {
    font-size : 50px;
}
#l5 {
    font-size : 20px;
}
'''



if __name__ == "__main__":
    SPLab()
    app = QApplication(sys.argv)
    app.setStyleSheet(Stylesheet)
    mwin = MainWindow()
    mwin.show()
    print("start")
    sys.exit(app.exec_())
→ Ссылка