0

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)

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Do remember to call fileno instead of hard-coding the fd value. It's not necessarily 0. sys.stdin may have been reassigned, and there can be other reasons that stdin isn't fd 0.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.