1

Can anyone tell me why this code runs differently in python console than IDLE?

print('Do not press enter before the program says go.\n', end = '')
try:
    while True:
        input('Ready?')
        print('Starting', end = '')
        for i in range(secrets.randbits(3)):
            time.sleep(1)
            print(' .', end = '')
        now = datetime.datetime.now()
        input('\nGo!')
        print('\nReaction: {}'.format(datetime.datetime.now()-now))
except KeyboardInterrupt:
    print('Exiting.')

This is the output in IDLE which works the way I expect:

Do not press enter before the program says go.
Ready?
Starting . .
Go!

Reaction: 0:00:00.328174

But when in the console I get the same overall output but the dots do not show up one after the other, instead they all appear at once with go.Can anyone explain this strange behaviour. I am running Python 3.6.2 if that helps.

I do have a way to test if the program is running from IDLE or not which returns true if in idle and false if not in idle:

def inIDLE():
    import sys
    if 'idlelib.run' in sys.modules:
        return True
    else:
        return False
Lasagnenator
  • 168
  • 2
  • 11
  • IDLE has a few quirks; the plain console is behaving correctly. If you don't want your dots to appear all at once you can tell the console to flush its output: `print(' .', end = '', flush=True)` – PM 2Ring Sep 30 '17 at 06:21
  • Ahh, now that is the solution that I was looking for. I had no idea how to use flush but now I do. Thanks for the help @PM2Ring – Lasagnenator Sep 30 '17 at 10:50

1 Answers1

1

Because it's a GUI program (running on Tkinter) IDLE has a few quirks; the plain console is actually behaving correctly, since output to stdout is normally line-buffered.

If you don't want your dots to appear all at once you can tell the console to flush its output:

print(' .', end = '', flush=True)

Alternatively, you can print to stderr which is normally not buffered:

import sys
#...
print(' .', end = '', file=sys.stderr)

In the console, you can select unbuffered stdout by passing the -u option to the interpreter, see python3 -h for details.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182