2

Какого-то заготовленного кода нету. Суть в том, что, при выполнение Python скрипта происходит проверка текстового файла на наличие определённых условий и выводит результат в консоль с помощью print():

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

Как можно постоянно выводить текст из консоли в виджет Pyqt5?


code.py:

from datetime import datetime
from colorama import Fore, Style, init
import time, os, re
import csv, asyncio
import colorama
from valve.source.a2s import ServerQuerier, NoResponseError
import yaml
import config

pdeath = '.*?Got character ZDOID from (\w+) : 0:0'
sevent = '.*?Got character ZDOID from (\\w+)\\b(?!:)'
pkill = '.*? (\\w+):(\\w+)\\b(?!:)'
revent = '.*? (\w+):(\w+):(\w+)'
log = config.file
dlog = config.players_log
rlog = config.rewards_log
path_player = 'csv/playerstats.csv'
path_death = 'csv/deathlog.csv'
path_killed = 'csv/killedlog.csv'
path_reward = 'csv/rewardslog.csv'

colorama.init()

async def timenow():
    now = datetime.now()
    gettime = now.strftime("%d/%m/%Y %H:%M:%S")
    return gettime

async def writecsv():
    while True:    
        try:
            with ServerQuerier(config.SERVER_ADDRESS) as server:
                with open('csv/playerstats.csv', 'a', newline='') as f:
                    csvup = csv.writer(f, delimiter=',')  
                    curtime, players = await timenow(), server.info()['player_count']
                    csvup.writerow([curtime, players])
                    print(f"{Fore.MAGENTA}{curtime} > Player count: {players}{Style.RESET_ALL}") ############################
        except NoResponseError:
            with open('csv/playerstats.csv', 'a', newline='') as f:
                csvup = csv.writer(f, delimiter=',')  
                curtime, players = await timenow(), '0'
                csvup.writerow([curtime, players])
                print(Fore.RED + curtime, 'Unable to connect to server' + Style.RESET_ALL) ############################
        await asyncio.sleep(60)

async def deathcount():
    while True:           
        with open(log, encoding='utf-8', mode='r') as f:
            f.seek(0,2)
            while True:
                line = f.readline()
                if(re.search(pdeath, line)):
                    pname = re.search(pdeath, line).group(1)
                    curtime = await timenow()
                    with open('csv/deathlog.csv', 'a', newline='', encoding='utf-8') as dl:
                        deathup = csv.writer(dl, delimiter=',')
                        deathup.writerow([curtime, pname])
                        print(Fore.CYAN + f"{curtime} > {pname} умер!" + Style.RESET_ALL) ############################
                await asyncio.sleep(0.2)

async def joinedcount():
    while True:
        with open(log, encoding='utf-8', mode='r') as f:
            f.seek(0,2)
            while True:

                line = f.readline()
                first_try = '.*? User (\w+) connected.'
                second_try = '.*? User (\w+)\s(\w+) connected.'
                curtime = await timenow()

                if(re.search(first_try, line)):
                    player = re.search(first_try, line).group(1)
                    with open('csv/joinedcount.csv', 'a', newline='', encoding='utf-8') as j:
                        joinedup = csv.writer(j, delimiter=',')
                        joinedup.writerow([curtime, player])
                        print(Fore.LIGHTGREEN_EX + f"{curtime} > {Fore.WHITE}{player}{Fore.LIGHTGREEN_EX} присоединился на сервер! {Style.RESET_ALL}") ############################

                if(re.search(second_try, line)):
                    player = re.search(second_try, line).group(1), re.search(second_try, line).group(2)
                    player = f"{player[0]} {player[1]}"
                    with open('csv/joinedcount.csv', 'a', newline='', encoding='utf-8') as j:
                        joinedup = csv.writer(j, delimiter=',')
                        joinedup.writerow([curtime, player])
                        print(Fore.LIGHTGREEN_EX + f"{curtime} > {Fore.WHITE}{player}{Fore.LIGHTGREEN_EX} присоединился на сервер! {Style.RESET_ALL}") ############################

forma.py

# -*- coding: utf-8 -*-

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1186, 722)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.background = QtWidgets.QLabel(self.centralwidget)
        self.background.setGeometry(QtCore.QRect(-20, -180, 1321, 941))
        self.background.setStyleSheet("background-color: rgb(18, 18, 18);")
        self.background.setText("")
        self.background.setObjectName("background")
        self.PVELogs = QtWidgets.QPlainTextEdit(self.centralwidget)
        self.PVELogs.setGeometry(QtCore.QRect(80, 50, 491, 491))
        font = QtGui.QFont()
        font.setFamily("Fira Code")
        font.setPointSize(9)
        self.PVELogs.setFont(font)
        self.PVELogs.setStyleSheet("background-color: rgb(30, 30, 30);color: rgb(255, 255, 255);")
        self.PVELogs.setReadOnly(True)
        self.PVELogs.setObjectName("PVELogs")
        self.PVPLogs = QtWidgets.QPlainTextEdit(self.centralwidget)
        self.PVPLogs.setGeometry(QtCore.QRect(620, 50, 491, 491))
        font = QtGui.QFont()
        font.setFamily("Fira Code")
        font.setPointSize(9)
        self.PVPLogs.setFont(font)
        self.PVPLogs.setStyleSheet("background-color: rgb(30, 30, 30);color: rgb(255, 255, 255);")
        self.PVPLogs.setReadOnly(True)
        self.PVPLogs.setObjectName("PVPLogs")
        self.PVELabel = QtWidgets.QLabel(self.centralwidget)
        self.PVELabel.setGeometry(QtCore.QRect(80, 20, 211, 21))
        font = QtGui.QFont()
        font.setFamily("Consolas")
        font.setPointSize(10)
        font.setBold(True)
        font.setItalic(False)
        font.setWeight(75)
        self.PVELabel.setFont(font)
        self.PVELabel.setStyleSheet("color: rgb(255, 255, 255);")
        self.PVELabel.setObjectName("PVELabel")
        self.PVPLabel = QtWidgets.QLabel(self.centralwidget)
        self.PVPLabel.setGeometry(QtCore.QRect(620, 20, 211, 21))
        font = QtGui.QFont()
        font.setFamily("Consolas")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.PVPLabel.setFont(font)
        self.PVPLabel.setStyleSheet("color: rgb(255, 255, 255);")
        self.PVPLabel.setObjectName("PVPLabel")
        self.settings = QtWidgets.QPushButton(self.centralwidget)
        self.settings.setGeometry(QtCore.QRect(10, 690, 75, 23))
        self.settings.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
        self.settings.setObjectName("settings")
        self.offPVE = QtWidgets.QPushButton(self.centralwidget)
        self.offPVE.setGeometry(QtCore.QRect(230, 550, 121, 31))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(75)
        self.offPVE.setFont(font)
        self.offPVE.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
        self.offPVE.setObjectName("offPVE")
        self.onPVE = QtWidgets.QPushButton(self.centralwidget)
        self.onPVE.setGeometry(QtCore.QRect(90, 550, 121, 31))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(75)
        self.onPVE.setFont(font)
        self.onPVE.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
        self.onPVE.setObjectName("onPVE")
        self.onPVP = QtWidgets.QPushButton(self.centralwidget)
        self.onPVP.setGeometry(QtCore.QRect(630, 550, 121, 31))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(75)
        self.onPVP.setFont(font)
        self.onPVP.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
        self.onPVP.setObjectName("onPVP")
        self.offPVP = QtWidgets.QPushButton(self.centralwidget)
        self.offPVP.setGeometry(QtCore.QRect(770, 550, 121, 31))
        font = QtGui.QFont()
        font.setFamily("Arial")
        font.setBold(True)
        font.setWeight(75)
        self.offPVP.setFont(font)
        self.offPVP.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
        self.offPVP.setObjectName("offPVP")
        self.timelaunch = QtWidgets.QLabel(self.centralwidget)
        self.timelaunch.setGeometry(QtCore.QRect(810, 690, 211, 21))
        font = QtGui.QFont()
        font.setBold(False)
        font.setItalic(False)
        font.setWeight(50)
        font.setStrikeOut(False)
        self.timelaunch.setFont(font)
        self.timelaunch.setStyleSheet("color: rgb(255, 255, 255); background-color: rgb(18, 18, 18);")
        self.timelaunch.setObjectName("timelaunch")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "VALHEIMBY BOT - SERVERS LOG"))
        self.PVELogs.setPlainText(_translate("MainWindow", "QPlainTextEdit"))
        self.PVPLogs.setPlainText(_translate("MainWindow", "QPlainTextEdit"))
        self.PVELabel.setText(_translate("MainWindow", "PVE Logs:"))
        self.PVPLabel.setText(_translate("MainWindow", "PVP Logs:"))
        self.settings.setText(_translate("MainWindow", "Настройки"))
        self.offPVE.setText(_translate("MainWindow", "Завершить PVE.py"))
        self.onPVE.setText(_translate("MainWindow", "Запустить PVE.py"))
        self.onPVP.setText(_translate("MainWindow", "Запустить PVP.py"))
        self.offPVP.setText(_translate("MainWindow", "Завершить PVP.py"))
        self.timelaunch.setText(_translate("MainWindow", "Время с момента запуска: {time_launch}"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
2

1 ответ 1

1

Для начала, QTextEditLogger, можно сделать другим?

Хотя это уже другой вопрос, но я отвечу: 'Да, можно'.

import logging
import sys
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(900, 400)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(110, 240, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.plainTextEdit = QtWidgets.QPlainTextEdit(self.centralwidget)
        self.plainTextEdit.setGeometry(QtCore.QRect(10, 10, 291, 131))
        self.plainTextEdit.setObjectName("plainTextEdit")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(130, 180, 47, 13))
        self.label.setObjectName("label")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))
        self.label.setText(_translate("MainWindow", "TextLabel"))


class QTextEditLogger123(logging.Handler):
    def __init__(self, parent):
        super().__init__()

        self.widget = parent.plainTextEdit 
        self.widget.setReadOnly(True)

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

   
# +++  vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
class QTextEditLogger(logging.Handler):
    def __init__(self, parent):
        super().__init__()
 
#        self.PVELogs = QtWidgets.QPlainTextEdit(self.centralwidget)
        self.PVELogs = QtWidgets.QPlainTextEdit(parent.centralwidget)                # +++
        
        self.PVELogs.setGeometry(QtCore.QRect(40, 50, 541, 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")
        
        parent.layout.addWidget(self.PVELogs, 1, 0)                                  # +++
 
        self.PVPLogs = QtWidgets.QPlainTextEdit(parent.centralwidget)
        self.PVPLogs.setGeometry(QtCore.QRect(610, 50, 541, 491))
        font = QtGui.QFont()
        font.setFamily("Consolas")
        font.setPointSize(10)
        self.PVPLogs.setFont(font)
        self.PVPLogs.setStyleSheet("background-color: rgb(30, 30, 30); color: rgb(255, 255, 255);")
        self.PVPLogs.setReadOnly(True)
        self.PVPLogs.setPlainText("")
        self.PVPLogs.setObjectName("PVPLogs")
        
        parent.layout.addWidget(self.PVPLogs, 1, 1)                                  # +++
 
    def emit(self, record):
        msg0 = self.format(record)
        self.PVELogs.appendPlainText(msg0)
 
        msg1 = self.format(record)
        self.PVPLogs.appendPlainText(msg1)
# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        


class ExampleApp(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()

        self.setupUi(self)
        
        self.layout = QtWidgets.QGridLayout(self.centralwidget)          # +++
#        self.layout.addWidget(self.plainTextEdit, 0, 0, 1, 2)
        self.layout.addWidget(self.label, 2, 0)                          # +++
        self.layout.addWidget(self.pushButton, 2, 1)                     # +++


        logTextBox = QTextEditLogger(self)
        logTextBox.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        logging.getLogger().addHandler(logTextBox)
        logging.getLogger().setLevel(logging.DEBUG)

        # Делает QPlainTextEdit только для вывода
        self.plainTextEdit.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse) 

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

        logging.debug("Это сообщение об отладке")
        logging.info(u'This is an info message')

    def func1(self):
        # Создаем поток
        self.thread.start()

    def func2(self, value):
        logging.info("Передано из потока -> {}".format(value)) 


class WorkThread(QtCore.QThread):
    ''' Потоковая задача '''
    threadSignal = QtCore.pyqtSignal(int)

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

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


if __name__=='__main__':
    app = QtWidgets.QApplication(sys.argv)  
    window = ExampleApp()                   
    window.show()                           
    sys.exit(app.exec_())

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

2
  • Большое спасибо!
    – iframe
    Commented 7 июн. 2021 в 18:18
  • @hoojpop пожалуйста
    – S. Nick
    Commented 7 июн. 2021 в 18:19

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.