在windows python3中将stdin作为二进制文件读取
我有一个在linux中将stdin作为二进制文件读取的代码:在windows python3中将stdin作为二进制文件读取,windows,python-3.x,stdin,file-handling,Windows,Python 3.x,Stdin,File Handling,我有一个在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)
#! /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()
windows操作系统的替代方案是什么?
我不想使用sys.stdin.buffer.read()
把它当作是强制使用的,比如<代码>打开(文件名)<代码> < /p> < p> <代码> sys .STDIN < /COD>,<代码> sys .StdOut<<代码>,和<代码> sys .STDRR 每个都有一个<代码>文件()/<代码>方法,返回它们的文件描述符号。(0、1和2) 在python中,可以使用缓冲区的
fileno
作为open
的路径目标
另外,正如@eryksun所提到的,在调用open
时,您可能希望传递closefd=False
,这样当退出带有块的时,sys.stdin
的底层文件描述符不会关闭
例如:
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)
sys.stdin
、sys.stdout
和sys.stderr
都有一个fileno()
方法返回其文件描述符编号。(0、1和2)
在python中,可以使用缓冲区的fileno
作为open
的路径目标
另外,正如@eryksun所提到的,在调用open
时,您可能希望传递closefd=False
,这样当退出带有块的时,sys.stdin
的底层文件描述符不会关闭
例如:
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)
一个好的选择是使用流的.buffer
成员访问二进制版本:
stdin_buffer = sys.stdin.buffer
def read_input():
while True:
inp = stdin_buffer.read(4)
if not inp: break
print('got :' , inp)
我现在看到你在问题“我不想使用sys.stdin.buffer.read()
”中写道,但仍然决定发布这个答案,因为对于许多其他遇到这个问题的人来说,这实际上是最好的解决方案,而且很容易在你的问题中漏掉对它的简短提及(这正是发生在我身上的!)。有什么原因不适合您吗?一个好的选择是使用流的.buffer
成员访问二进制版本:
stdin_buffer = sys.stdin.buffer
def read_input():
while True:
inp = stdin_buffer.read(4)
if not inp: break
print('got :' , inp)
我现在看到你在问题“我不想使用sys.stdin.buffer.read()
”中写道,但仍然决定发布这个答案,因为对于许多其他遇到这个问题的人来说,这实际上是最好的解决方案,而且很容易在你的问题中漏掉对它的简短提及(这正是发生在我身上的!)。有什么原因不适合您吗?请记住调用fileno
,而不是硬编码fd值。不一定是0sys.stdin
可能已重新分配,并且可能有其他原因导致stdin
不是fd 0。请记住调用fileno
而不是硬编码fd值。不一定是0sys.stdin
可能已被重新分配,可能还有其他原因导致stdin
不是fd 0。