简体   繁体   English

在windows python3中将stdin作为二进制文件读取

[英]Reading stdin as binary file in windows python3

I have a code to read stdin as binary file in linux:我有一个代码可以在 linux 中将 stdin 作为二进制文件读取:

#! /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? Windows 操作系统的替代品是什么? I dont want to use sys.stdin.buffer.read() Consider it as it is compulsary for me to use it like open(file_name)我不想使用sys.stdin.buffer.read()考虑一下,因为我必须像open(file_name)一样使用它

sys.stdin , sys.stdout , and sys.stderr each have a fileno() method which returns their file descriptor number. sys.stdinsys.stdoutsys.stderr每个都有一个fileno()方法,它返回它们的文件描述符编号。 (0, 1, and 2) (0、1 和 2)

In python you can use the buffer's fileno as the path destination for open .在 python 中,您可以使用缓冲区的fileno作为open的路径目标。

Also, as @eryksun mentioned, 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.此外,正如@eryksun 所提到的,您可能希望在调用open时传递closefd=False以便在退出with块时不会关闭sys.stdin的底层文件描述符。

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)

A good option is to use the .buffer member of the stream to get access to a binary version:一个不错的选择是使用流的.buffer成员来访问二进制版本:

stdin_buffer = sys.stdin.buffer
def read_input():
    while True:
        inp = stdin_buffer.read(4)
        if not inp: break
        print('got :' , inp)

I now see you wrote in the question "I dont want to use sys.stdin.buffer.read() " but still decided to post this answer because, for many other people that come across this question, that is actually the best solution and it's very easy to miss the brief mention of it in your question (which is exactly what happened to me!).我现在看到您在问题“我不想使用sys.stdin.buffer.read() ”中写道,但仍然决定发布此答案,因为对于遇到此问题的许多其他人来说,这实际上是最佳解决方案,并且在您的问题中很容易错过对它的简短提及(这正是我遇到的情况!)。 Is there any reason that wouldn't work for you?有什么理由不适合你吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM