How can I print from a Python 2.7 script called from Bash in PyCharm?

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 launching the latter (for example, using the Run menu item) from PyCharm (2016.1) does not output until the entire script is completed (after about 10 seconds).

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

+2
source share
2 answers

It 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, which are automatically cleared after each print. A.

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 
+4
source

Just add to @MartijnPieters answer regarding PyCharm:

In PyCharm, set the launch configuration for the shell script in the Run β†’ Change configurations section, for example:

enter image description here

Pay attention to PYTHONUNBUFFERED=1 .

You may need to first add the Bash launch configuration to the Accessories menu on the left.

+1
source

All Articles