1

I am working on a very simple interface to explore/graph csv files. My aim is ultimately to explore, not to build software as I am not a developer, more of a "desperate user" :-)

I am leveraging the code found in this example

These are my first steps both in Python and in GUI, so I tend to put print messages in my calls so that I can more or less track what is happening. And this is where I found a strange behavior if I run the code from within Spyder.

import sys
import os
from PyQt4 import QtGui
import pandas as pd
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt

# QtGui.QDialog

class Window(QtGui.QDialog):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some extra button to mess around
        self.button= QtGui.QPushButton('Push Me')
        self.button.clicked.connect(self.do_print)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)


    def do_print(self):
        print('Hello World!!')


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

The strange behavior is that if I push the button once, nothing happens on the Ipython console. By the second time I push, then two "Hello World!" printouts appear.

If, on the other hand, I just launch my script from within a Windows Shell:

python my_simple_test.py

Then everything works as expected.

What am I then doing wrong from within Spyder?

Thanks, Michele

Community
  • 1
  • 1
Michele Ancis
  • 1,265
  • 4
  • 16
  • 29

1 Answers1

0

IPython buffers stdout a bit differently from a terminal. When something is printed, it looks at how long it has been since it last flushed the buffer, and if it's longer than some threshold, it flushes it again. So the second time you click the button, it flushes stdout, and you see both outputs.

You can force it to flush immediately like this:

print('Hello World!!')
sys.stdout.flush()
Thomas K
  • 39,200
  • 7
  • 84
  • 86
  • Yep, that made it. However, I am not sure of the meaning of "looks at how long" in this context. How long, in terms of time? In terms of bytes? Thanks for your reply!! – Michele Ancis Jul 27 '15 at 21:31