How to capture the string of the processes that the python interpreter is executing in cmd?

1

I do not know if I am very clear with the question, basically I would like to know if it is possible to capture the string of the processes that python is executing inside the cmd, something like the following:

Example:

Let's say that within a script.py we have the following line os.system('pip install google') this line will return an output in the cmd.

something like this:

What can I do to capture that text that is displayed in the cmd and show it for example in a QLabel for example

I hope to be clear in the explanation

    
asked by Revsky01 29.08.2018 в 04:57
source

2 answers

3

In this another answer I signal because os.system() does not work and I signal alternatives. But in this case I will propose using QProcess because it has the advantage that it uses the Qt event-loop avoiding the GUI to be blocked, in the following example I show the output in a QTextEdit since it will look better than the QLabel.

from PyQt5 import QtCore, QtGui, QtWidgets

class Widget(QtWidgets.QWidget):
    def __init__(self, parent = None):
        super(Widget, self).__init__(parent)
        layout = QtWidgets.QVBoxLayout(self)
        self.te = QtWidgets.QTextEdit()
        self.te.setReadOnly(True)

        button = QtWidgets.QPushButton("Ejecutar comando")
        button.clicked.connect(self.onClicked)

        layout.addWidget(self.te)
        layout.addWidget(button)

        self.process = QtCore.QProcess(self)
        self.process.readyReadStandardOutput.connect(self.onReadyReadStandardOutput)

    def onClicked(self):
        self.process.start("pip install google")

    def onReadyReadStandardOutput(self):
        self.te.append(self.process.readAllStandardOutput().data().decode())



if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    ex = Widget()
    ex.show()
    sys.exit(app.exec_())

    
answered by 29.08.2018 / 07:05
source
0

While os.system () shows the output of the command on the screen and only returns its error code, os.popen () opens a pipe of for reading (by default) that allows reading the output of the process as if it's a python file.

A small example would be:

import os
salida = os.popen('echo Hola').read()
print(salida) # Muestra 'Hola'
    
answered by 29.08.2018 в 06:11