0

In Python 2.7, if I use print statement followed by comma as the following:

print('Generation ...'),
X, y = generate_dataset(num_samples)
print('Done!')

The first print print('Generation ...'), will NOT show up in the terminal until X, y = generate_dataset(num_samples) is finished! How can I force the print to immediately step by step with the existence of comma?

mx0
  • 6,445
  • 12
  • 49
  • 54
Dave
  • 554
  • 1
  • 6
  • 13
  • you cannot do it, if you keep comma print statement will wait until x,y are evaluated and only then print statement can show the result – Tilak Putta Dec 06 '17 at 18:57
  • 2
    https://stackoverflow.com/questions/230751/how-to-flush-output-of-python-print You'll probably have to manually flush output. Comma is not exactly relevant here since print is a side effect that doesn't need to wait for evaluation results. – Haochen Wu Dec 06 '17 at 19:10
  • `print "aaa",inf_loop()` does print to screen before I hit Ctrl+C in Jupyter notebook and `print "aa", sys.stdout.flush(), inf_loop()` does print to screen in interactive python shell. – Haochen Wu Dec 06 '17 at 19:12

2 Answers2

0
import sys

print "I'm going to do something that takes a long time...",
sys.stdout.flush()
really_time_consuming_function()
print "done!"
PaulMcG
  • 62,419
  • 16
  • 94
  • 130
0

You can also run the python interpreter with the -u flag if you don't want to handle this in code.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80