H
H
hoojpop2021-06-10 10:48:28
Python
hoojpop, 2021-06-10 10:48:28

RuntimeWarning: enable tracemalloc to get object allocation trace, how to fix?

I work with PyQt5. I am making a logging application. There is a problem with thread and asyncio .
The task is that when the button is clicked, an asynchronous function should be launched that works in a constant cycle to check the files and output the received data obtained through the conditions.

There is an asynchronous function that I call through a thread:

async def deathcount():
    PLAYER_DEATH = '.*?Got character ZDOID from (\w+) : 0:0'
    log = "c:/.../files/log.txt"
    while True:     
        with open(log, encoding='utf-8', mode='r') as f:
            f.seek(0,2)
            while True:
                line = f.readline()
                if(re.search(PLAYER_DEATH, line)):
                    pname = re.search(PLAYER_DEATH, line).group(1)
                    with open(file, 'a', newline='', encoding='utf-8') as dl:
                        ... ...
                        log(f"{gettime}{pname} умер!")
                await asyncio.sleep(0.2)


PLAYER_DEATH- a variable that contains a string with a regular expression.
In a constant loop, log.txt is checked for the presence of a line from PLAYER_DEATH .

When you click on the button, according to the idea, the function should work deathcount(), which in the end, with a positive answer, should display the result - The result is displayed using the stream, and we call the function ( ) there: :log(f"{gettime}{pname} умер!")

deathcount()
basic.py
class QTextEditLogger(logging.Handler):

    def __init__(self, parent):
        super().__init__()

        self.PVELogs = QtWidgets.QPlainTextEdit(parent.centralwidget)
        self.PVELogs.setGeometry(QtCore.QRect(40, 50, 801, 491))
        font = QtGui.QFont()
        font.setFamily("Consolas")
        font.setPointSize(10)
        self.PVELogs.setFont(font)
        self.PVELogs.setStyleSheet("background-color: rgb(30, 30, 30); color: rgb(255, 255, 255);")
        self.PVELogs.setReadOnly(True)
        self.PVELogs.setPlainText("")
        self.PVELogs.setObjectName("PVELogs")

    def emit(self, record):
        msg = self.format(record)
        self.PVELogs.appendPlainText(msg)

class PVP(QtWidgets.QMainWindow, QWidget, MainInterface):
    def __init__(self):
        super().__init__()

        self.setupUi(self) #init gui

        # logging
        logTextBox = QTextEditLogger(self)
        #logTextBox.setFormatter(logging.Formatter(f'{gettime}%(message)s'))
        logging.getLogger().addHandler(logTextBox)
        logging.getLogger().setLevel(logging.DEBUG)

        root_logger= logging.getLogger()
        root_logger.setLevel(logging.DEBUG)
        handler = logging.FileHandler('PVPLog.log', 'w', 'utf-8') 
        handler.setFormatter(logging.Formatter('%(name)s, %(asctime)s, [%(levelname)s], %(message)s'))
        root_logger.addHandler(handler)

        self.PVELogs.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse) 

        self.thread = WorkThread()
        self.thread.threadSignal.connect(self.func2)           
        self.onPVE.clicked.connect(self.func1)      

    def func1(self):
        self.thread.start()

    def func2(self, value):
        deathcount() # Вызываем функцию ! ! !

class WorkThread(QtCore.QThread):
    threadSignal = QtCore.pyqtSignal(int)

    def __init__(self):
        super().__init__()

    def run(self):     
        for i in range(10):
            self.msleep(200)
            self.threadSignal.emit(i)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mw = PVP()
    mw.show()

    sys.exit(app.exec())
    
loop = asyncio.new_event_loop()
loop.create_task(deathcount())
asyncio.set_event_loop(loop)


At the end of the file, I created a new event loop, following the advice of this topic

. At the end of the asynchronous function, there is a wait ( await asyncio.sleep(0.2)).
But in the end, something is still wrong.

c:\..\..\..\programma\basic.py:132: RuntimeWarning: coroutine 'deathcount' was never awaited
  deathcount()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback


Tried calling the loop in the function itself func2:

def func2(self, value):
    loop = asyncio.new_event_loop()
    loop.create_task(deathcount())
    asyncio.set_event_loop(loop)


Already a different result, so even interesting lines appeared in the application:

C:\Users\Stepan\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py:667: RuntimeWarning: coroutine 'deathcount' was never awaited
  self._ready.clear()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback


60c1c3a922790329840224.png

-
All code
-

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2021-06-10
@LaRN

But it cannot be that after mw.show() is called, the control flow no longer returns to basyc.py until the widget is closed and the code
loop = asyncio.new_event_loop()
loop.create_task(deathcount())
asyncio.set_event_loop(loop )
is not executed.
Maybe it makes sense to move this code to the
if __name__ == "__main__" code:

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question