金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks
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.
posted on 2012-04-11 10:56 金庆 阅读(1799) 评论(0)  编辑 收藏 引用 所属分类: 6. Python

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理