Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

Using Windows Python from Cygwin

I've been using Cygwin on Windows recently. I want to use the Windows installation of Python, so during testing I'm using /cygdrive/c/Python26/python.exe myfile.py rather than python myfile.exe.

This is working almost perfectly, except for printing. When I run the Windows Python from Cygwin the output doesn't print until execution finishes. It works fine running in Windows Python from explorer.exe or cmd.exe, and it works in Cygwin using the Cygwin-installed Python (/bin/python.exe).

Is there a workaround for this? The important thing is to be able to run the Windows version, but I'd like to do it all from with Bash.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

One solution without changing the code is to turn off buffering in Python using the '-u' flag on the command line or setting the PYTHONUNBUFFERED environment variable.

export PYTHONUNBUFFERED=1

/cydrive/c/Python27/python.exe foo.py

or

/cydrive/c/Python27/python.exe -u foo.py

or run in interactive mode

/cydrive/c/Python27/python.exe -i foo.py

You will also not be able to run the Windows python.exe interactive mode in the Cygwin terminal. It will not bring up an interactive session, but will just hang. I find the best solution seems to be to use 'cygstart' (better than using the '-i' option):

cygstart /cygdrive/c/Python27/python.exe

And that seems to work with ipython as well (if installed):

cygstart /cygdrive/c/Python27/Scripts/ipython.exe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...