我有一个二进制原始数据文件in.dat
存储4个int32值。
$ xxd in.dat
00000000: 0100 0000 0200 0000 0300 0000 0400 0000 ................
我想把它们读入np.ndarray
,乘以2,然后用与in.dat
相同的原始二进制格式将它们写出到stdout。预期产出如下:
密码是这样的
#!/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
我错过了什么?
这是因为在中重定向文件时,stdin是可查找的(因为它不是TTY或管道,例如,它只是一个被赋予fd1的文件)。尝试使用
cat foo.txt | python3 test.py
vspython3 test.py <foo.txt
调用以下脚本(假设食品.txt包含一些文本):前者将出现以下错误:
^{pr2}$也就是说,对于你在这里所要做的,纽比是一种过分的杀戮。您可以通过几行和
struct
轻松实现这一点:编辑:也不需要
sys.exit(0)
。这是默认值。在如果使用
np.frombuffer
,它应该可以双向工作:在pipebytes.py在
现在
^{pr2}$不过,我怀疑这会复制数据。在
相关问题 更多 >
编程相关推荐