#142 – Fixing the stdout issue with Python on Cygwin

Hi everybody, so today I’ll do a quick article as well and I’ll talk about a bug fix for an issue I had since I installed Babun, which is using cygwin, on Windows. I had a weird issue where the output wouldn’t get printed, so I decided to investigate a little bit.


Where does the issue come from?

So I had to google a little bit to know the answer, most of the answers were inaccurate or gave a solution that didn’t work all the time. The most given answer was to simply use “python -i”, which forces a prompt even if stdin doesn’t seem to be a terminal. It kinda solved the issue for launching python in terminal mode but not for the output of my scripts.

I found a good answer on Stack Overflow of why the issue really happened:

The real problem is that when you run a command in any of the Cygwin terminal programs like mintty, they don't act as Windows Consoles. Only Windows Console-based ones like CMD or Console2 do that. So, with Cygwin terminals the Windows python.exe doesn't think it is talking to an interactive console.

That leads to buffering output instead of flushing buffers on every line as is done in interactive sessions. That is why Amro's adding the flush() on every line fixes the symptom, but means changing the code.

It basically means that since the Cygwin terminal doesn’t act as a window console, the output gets buffered rather than flushed every line.



If you have access to the script, you could clear the console before using it, but the easier method for me was to use the option “-u” on script launches, which gives an unbuffered stdout and stdin. I’ll use “-i” for the prompt mode as well, which will forces a prompt.

I also did setup cygstart as an alias which would help running the script in the ideal conditions if I wanted to launch a script longer.

alias pycyg3='cygstart /cygdrive/c/Users/ddxhu/AppData/Local/Programs/Python/Python36/python'

The issue with that solution is that it opens a window each time and that if the scripts has an error and gets killed, the window will close and I didn’t find a good way to keep the window open, maybe by using cmd.exe.

Leave a Reply

Your email address will not be published.