【问题标题】:porting numpy fromfile to python3 when reading from standard input从标准输入读取时将 numpy fromfile 移植到 python3
【发布时间】:2020-03-29 07:47:40
【问题描述】:

我正在将一些代码移植到 Python 3 并偶然发现了 numpy.fromfile(src) 的调用,当 src 是真实文件的句柄时它工作得很好,但当 srcsys.stdin 时失败。我将问题归结为以下两个命令,它们可以让您了解问题仅存在于 Python 3 中而不存在于 Python 2 中的原因:

$ echo 1 2 3 | python -c 'import numpy,sys; print(numpy.fromfile(sys.stdin, dtype=int, sep=" "))'
[1 2 3]
$ echo 1 2 3 | python3 -c 'import numpy,sys; print(numpy.fromfile(sys.stdin, dtype=int, sep=" "))'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
OSError: obtaining file position failed

当我查看 /usr/lib/python2.7/dist-packages/numpy/core/records.py 时,似乎即使在 Python2 版本的 numpy 中,它也显示为 fromfile:

文件对象必须支持随机访问(即它必须有 tell 和 seek 方法)。

所以我猜想上述与 Python2 一起工作的事实从未被支持。我想移植到 Python3 的代码仍然依赖于这个功能。

我尝试将sys.stdin 读入io.BytesIO,但这会导致io.UnsupportedOperation: fileno 出错。

我希望其他人也偶然发现了这个问题,我想请求一个简单的替换 numpy.fromfile(),即使在 Python3 上也可以从标准输入读取。当然其他项目已经必须实施解决方案?我没找到。

【问题讨论】:

    标签: python-3.x python-2.7 numpy


    【解决方案1】:

    您可以尝试像这样从stdin 读取字节:

    data = sys.stdin.buffer.read()
    

    然后使用numpy.frombuffer 阅读它。 (您还应该提供数据类型)

    arr = np.frombuffer(data, dtype=np.float)
    

    如果你正在读取文本数据,你可以这样做:

    data = sys.stdin.read()
    arr = numpy.fromstring(data, sep=" ")
    

    当您不提供 sep 时,它会以某种旧模式运行。

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 1970-01-01
      • 2013-03-30
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多