I've been getting into Python lately. One problem that I've encountered
under Windows, is that input redirection doesn't work if you use
the .py file association to run the script; e.g.:
C:\> foo.py < input.txt
There's a well-known input redirection bug. The fix is to explicitly use
python.exe to run the script.
A related problem for me was that stdin was opened as a text file,
not a binary file, so \r bytes were being discarded from binary input
files. The fix is to run python.exe -u (unbuffered binary input and
output).
I didn't want to hardcode the path to python.exe in a batch file,
so I came up with the following wrapper, which parses the output from
assoc .py and ftype Python.File.
Just place this batch file in the same directory as foo.py and call it
foo.bat.
@setlocal
@if (%_echo%)==() set _echo=off
@echo %_echo%
call :FindPythonExe
if "%PythonExe%"=="" (
echo Can't find python.exe
exit /B 1
)
set PythonFile=%~dpn0.py
"%PythonExe%" -u %PythonFile% %*
goto :EOF
:FindPythonExe
set PythonExe=
%PATH%
for %%i in (cmd bat exe) do (
if "%PythonExe%"=="" (
for %%j in (python.%%i) do set PythonExe=%%~$PATH:j
)
)
if "%PythonExe%"=="" call :AssocPy2Exe
goto :EOF
%PythonExe%
:AssocPy2Exe
call :AssocExtn2Exe .py
set PythonExe=%_exe%
goto :EOF
%1%_exe%
:AssocExtn2Exe
for /f "usebackq tokens=2 delims==" %%i in (`assoc %1`) do set _ftype=%%i
%1%*
for /f "usebackq tokens=2 delims==" %%i in (`ftype %_ftype%`) do set _rhs=%%i
for /f "tokens=1" %%i in ("%_rhs%") do set _exe=%%i
goto :EOF
Now you can run foo.bat < bar.jpg with the expected results.
Enjoy!
Update 2007/01/03:
The batchfile now searches %PATH% before looking
up the .py association.
Update 2007/01/12:
See here
for a significantly improved batchfile and for py2cmd.