Python3管道输入/输出打开np.ndarray公司原始二进制数据失败

2024-04-26 10:58:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二进制原始数据文件in.dat存储4个int32值。

$ xxd in.dat 
00000000: 0100 0000 0200 0000 0300 0000 0400 0000  ................

我想把它们读入np.ndarray,乘以2,然后用与in.dat相同的原始二进制格式将它们写出到stdout。预期产出如下:

^{pr2}$

密码是这样的

#!/usr/bin/env python3

import sys
import numpy as np

if __name__ == '__main__':
    y = np.fromfile(sys.stdin, dtype='int32')
    y *= 2
    sys.stdout.buffer.write(y.astype('int32').tobytes())
    exit(0)

我发现它和<一起工作

$ python3 test.py <in.dat >out.dat

但它不适用于管道|。错误信息来了。

$ cat in.dat | python3 test.py >out.dat
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    y = np.fromfile(sys.stdin, dtype='int32')
OSError: obtaining file position failed

我错过了什么?


Tags: inpytestimportnpstdinstdoutsys
2条回答

这是因为在中重定向文件时,stdin是可查找的(因为它不是TTY或管道,例如,它只是一个被赋予fd1的文件)。尝试使用cat foo.txt | python3 test.pyvspython3 test.py <foo.txt调用以下脚本(假设食品.txt包含一些文本):

import sys

sys.stdin.seek(1)
print(sys.stdin.read())

前者将出现以下错误:

^{pr2}$

也就是说,对于你在这里所要做的,纽比是一种过分的杀戮。您可以通过几行和struct轻松实现这一点:

import struct
import sys

FORMAT = '@i'


def main():
    try:
        while True:
            num = struct.unpack(FORMAT, sys.stdin.buffer.read(struct.calcsize(FORMAT)))
            sys.stdout.buffer.write(struct.pack(FORMAT, num * 2))
    except EOFError:
        pass

if __name__ == '__main__':
    main()

编辑:也不需要sys.exit(0)。这是默认值。在

如果使用np.frombuffer,它应该可以双向工作:

在pipebytes.py在

import numpy as np
import sys
print(np.frombuffer(sys.stdin.buffer.read(), dtype=np.int32))

现在

^{pr2}$

不过,我怀疑这会复制数据。在

相关问题 更多 >