2

For example if I have a python script test.py containing

import time

print 'foo'
time.sleep(5)

print 'bar'
time.sleep(5)

and a shell script run_test.sh containing

#!/usr/bin/env bash

python test.py

then running the latter (using the Run menu item for example) from within PyCharm (2016.1) prints no output until the entire script has completed (after about 10 seconds).

Is there a way to print output as my shell script runs?

Will
  • 24,082
  • 14
  • 97
  • 108
orome
  • 45,163
  • 57
  • 202
  • 418

2 Answers2

4

Looks like you need to explicitly flush the buffer:

import sys

print 'foo'
sys.stdout.flush()
time.sleep(5)

print 'bar'
sys.stdout.flush()
time.sleep(5)

See Disable output buffering for Python 2 solutions that auto-flush after every print.

In your case, since you control the bash file that runs Python, just add -u or set PYTHONUNBUFFERED=1:

python -u test.py

or

PYTHONUNBUFFERED=1 python test.py
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Just to add to @MartijnPieters' answer with regard to PyCharm:

In PyCharm, set the run configuration for the shell script under Run->Edit Configurations, like so:

enter image description here

Note the PYTHONUNBUFFERED=1.

You may have to first add a Bash run configuration under the Defaults menu on the left.

Will
  • 24,082
  • 14
  • 97
  • 108