Windows上Python读取stdin出错

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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值