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調(diào)用就正常:
> type input.txt | python replace.py
原因是cmd.exe通過后綴關(guān)聯(lián)運行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.
(金慶的專欄)
一段簡單的代碼,讀取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調(diào)用就正常:
> type input.txt | python replace.py
原因是cmd.exe通過后綴關(guān)聯(lián)運行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.