'Reading stdin as binary file in windows python3
I have a code to read stdin as binary file in linux:
#! /usr/bin/python3
stdin_file = '/dev/stdin'
def read_input():
with open(stdin_file, mode='rb') as f:
while True:
inp = f.read(4)
if not inp: break
print('got :' , inp)
read_input()
what could be its alternative for windows OS?
I dont want to use sys.stdin.buffer.read()
Consider it as it is compulsary for me to use it like open(file_name)
Solution 1:[1]
sys.stdin, sys.stdout, and sys.stderr each have a fileno() method which returns their file descriptor number. (0, 1, or 2).
In python you can use the buffer's fileno as the path destination for open.
Also, as @Eryk Sun mentioned in a comment, you probably want to pass closefd=False when calling open so the underlying file descriptor for sys.stdin isn't closed when exiting the with block.
For example:
import sys
fileno = sys.stdin.fileno()
print(fileno)
# prints 0
# Open stdin's file descriptor number as a file.
with open(fileno, "rb", closefd=False) as f:
while True:
inp = f.read(4)
if not inp:
break
print("Got:", inp)
Solution 2:[2]
Even though you said in your question "I dont want to use sys.stdin.buffer.read()", this might be useful for other users coming to this answer..
A good option is to use the .buffer member of the stream to get access to a binary version:
stdin_buffer = sys.stdin.buffer
def read_input():
while True:
inp = stdin_buffer.read(4)
if not inp: break
print('got :' , inp)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Neuron |
| Solution 2 | Neuron |
