【问题标题】:Implementing a file-like object that writes to a queue实现写入队列的类文件对象
【发布时间】:2019-08-22 12:54:47
【问题描述】:

我想并行化这段代码:

import numpy as np
import requests

# the 'in memory file' I use at the moment
bytesIO = io.BytesIO()

data = np.random.randint(0, 256, (30, 30))
np.savez(bytesIO, data=data)

# go to the beginning of the buffer again
bytesIO.seek(0)
# upload the file to a different server
requests.post("http://example.org/, files={'file': bytesIO},
              data={'filename': 'My_File'})

在这里

  1. 数据已生成,
  2. 数据在请求中发送。

我希望数据在被序列化到缓冲区时被传输。可能使用 2 个线程,通过 queue 连接。

对于传输,请求支持streaming uploads

但是np.savezrequests 都希望有一个类似文件的对象来读取/写入。队列不是文件式的,BytesIO 不是线程安全的。

解决这个问题的最佳方法是什么?

【问题讨论】:

    标签: python multithreading io python-multithreading


    【解决方案1】:

    将队列包装在自定义的类似文件的对象中。按照文档。这个问题有更多细节:Creating a custom file like object python suggestions?

    【讨论】:

    • 是的,我看到了那个,但它也没有真正说明需要什么。据说一方面它只需要实现write,另一方面只需实现read,但这真的足够吗?文档中的规范非常不具体。
    • 这取决于什么代码将使用类文件对象。如果该代码仅使用read,那么您只需要实现 read 方法
    • 我会尝试的,但我发现依靠这样的反复试验非常不满意。最好有一个适当的接口规范,更像是在 java 中。因为现在它会变得一团糟。如果我想将此代码作为库提供,我不知道需要实现哪些方法以及可以省略哪些方法。
    • Duck 打字有时会很不方便。
    猜你喜欢
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2011-03-10
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    相关资源
    最近更新 更多