Windows上Python读取stdin出错
(金庆的专栏)
一段简单的代码,读取stdin, 替换输出到stdout:
#!/usr/bin/env python
import os, sys
input_file = sys.stdin
output_file = sys.stdout
for s in input_file:
output_file.write(s.replace("abc", "def"))
代码改自CookBook的
Recipe 2.3. Searching and Replacing Text in a File
在Linux上运行正常:
$ cat input.txt | ./replace.py
但是在Windows的Dos窗口运行会报错:
> type input.txt | replace.py
Traceback...
for s in input_file:
IOError: [Errno 9] Bad file descriptor
如果用python调用就正常:
> type input.txt | python replace.py
原因是cmd.exe通过后缀关联运行py文件存在问题。
详见:Bad pipe filedescriptor when reading from stdin in python
http://stackoverflow.com/questions/1057638/bad-pipe-filedescriptor-when-reading-from-stdin-in-python
It seems that stdin/stdout redirect does not work when starting from a file association. This is not specific to python, but a problem caused by win32 cmd.exe.