October 8th, 2013, 12:12 PM
Help with redirecting subprocess stdout
Hi Folks this is my first ever Python Post in any forum...
I have been busy learnin Pyhon in conjunction with PYQT4 and find it very usefull, however Ive come up against a brick wall...
What I am trying to do is capture the terminal (stdout) output of a subprocess and display it in a QTextEdit box.
The process I am interested in is an Arch Linux process called pacman.
Normally you would type in a terminal: pacman -Syy to update the central package database. The process gives a streaming text output to the terminal.
I want to capture this stream in a PyQt Gui and display it.
Any help would be great...so far I have this code:
from PyQt4 import QtGui, QtCore, uic
oldstdout = sys.stdout
sys.stdout = io.StringIO()
print("Here is some text")
#process = subprocess.Popen(['python','-h'])
process = subprocess.Popen(['pacman','-Syy'])
sys.stdout = oldstdout
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MyWindow()
I get the output from the print command but the subprocess command output goes straight to the terminal....
October 9th, 2013, 01:52 AM
I'm fairly sure you're using python3.
I'm also fairly sure you can use
instead of that old trick of moving sys.stdout around. But anyway, that's not the problem. You need stdout of the subprocess. And you get that by reading the subprocess module over and over. And then some more.
with io.StringIO() as capture:
print('whatever', file = capture)
You might be able to use
output = subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False, timeout=None)
Otherwise, you might need
I'm sleepy. You can wade through it. Maybe the example half way down is useful:
with Popen(["ifconfig"], stdout=PIPE) as proc:
[/code] are essential for python code and Makefiles!
October 10th, 2013, 07:58 AM
Thank you very much I will try this....
I developed another solution using an embeded Terminal (xterm)
I created a frame QWidget in QT designer called "win" and embeded xterm thus:
os.system("xterm -into %d -geometry 60x20 -sb -e 'python'&" % wid)
This gives the output of the command 'python' to the embeded terminal which is so cool !!
Will try your solution though as it will be neater to get the output in a Text Box.