Question

Why do I never get the readyReadStandardOutput signal when I run the following?

import os, sys, textwrap

from PyQt4 import QtGui, QtCore

out_file = open("sleep_loop.py", 'w')
out_file.write(textwrap.dedent("""
    import time

    while True:
        print "sleeping..."
        time.sleep(1)"""))
out_file.close()

def started():
    print "started"

def on_error(error):
    errors = ["Failed to start", "Crashed", "Timedout", "Read error", 
              "Write Error", "Unknown Error"]
    print "error: ", errors[error]              

def on_state_change(new_state):
    states = ["Not running", "Starting", "Running"]
    print "new state: ", states[new_state]

def on_out():
    print "got out"

proc = QtCore.QProcess()
sig = QtCore.SIGNAL
proc.connect(proc, sig("started()"), started)
proc.connect(proc, sig("error(ProcessError)"), on_error)
proc.connect(proc, sig("readyReadStandardOutput()"), on_out)
proc.connect(proc, sig("stateChanged(ProcessState)"), 
             on_state_change)
proc.start("python sleep_loop.py")

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.show()
app.exec_()

proc.close()
Was it helpful?

Solution

Two problems here:

  1. You should create QApplication instance before creating everything else.
  2. Your child process is buffering its output.

Here is the fixed code, only two lines changed:

  1. app = QApplication moved before proc = QProcess
  2. child process now has sys.stdout.flush()

And now everything works as you expected:

import os, sys, textwrap

from PyQt4 import QtGui, QtCore

out_file = open("sleep_loop.py", 'w')
out_file.write(textwrap.dedent("""
    import time, sys

    while True:
        print "sleeping..."
        sys.stdout.flush()
        time.sleep(1)"""))
out_file.close()

def started():
    print "started"

def on_error(error):
    errors = ["Failed to start", "Crashed", "Timedout", "Read error", 
              "Write Error", "Unknown Error"]
    print "error: ", errors[error]              

def on_state_change(new_state):
    states = ["Not running", "Starting", "Running"]
    print "new state: ", states[new_state]

def on_out():
    print "got out"

app = QtGui.QApplication(sys.argv)
proc = QtCore.QProcess()
sig = QtCore.SIGNAL
proc.connect(proc, sig("started()"), started)
proc.connect(proc, sig("error(ProcessError)"), on_error)
proc.connect(proc, sig("readyReadStandardOutput()"), on_out)
proc.connect(proc, sig("stateChanged(ProcessState)"), 
             on_state_change)
proc.start("python sleep_loop.py")

widget = QtGui.QWidget()
widget.show()
app.exec_()

proc.close()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top