Windows上Python讀取stdin出錯

來源:互聯網
上載者:User
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.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.