【问题标题】:Is there a way to make StringIO reading blocking有没有办法让 StringIO 读取阻塞
【发布时间】:2012-04-13 08:30:22
【问题描述】:

我搜索了文档并四处搜索,但没有任何关于阻塞 StringIO 对象的说法。

我可以创建自己的类似文件的对象,该对象只是简单地包裹 StringIO,但最好的方法是如何使其阻塞?我知道的唯一方法是使用 while 循环和 time.sleep(0.1) 直到有可用数据。

【问题讨论】:

  • 究竟是什么会阻止它?您正在从字符串中读取数据。
  • StringIO 是一个类似文件的对象,所以它都有一个 '' EOF 和一个 .close() 方法,它使所有其他 read() 引发异常,我希望 EOF 只是阻塞而不是..返回 EOF。
  • 也许你想要一个管道来代替。
  • 我想问你如何期望 StringIO 对象在字符串不可变时解除阻塞,但后来我实际上查看了文档,发现这个限制仅适用于快速实现,@987654322 @,您可以读取或写入,但不能同时读取。我想你有另一个线程可以写。
  • 是的,我有另一个线程正在阅读它。它必须是跨平台的,否则我可以使用仅适用于 unix 的“管道”模块。因此,使用阻塞创建我自己的类似文件的对象是我当时采用的最佳方法。 sleep(0.1) 方法最适合吗?

标签: python blocking stringio


【解决方案1】:
import os

r, w = os.pipe()
r, w = os.fdopen(r, 'rb'), os.fdopen(w, 'wb')

完全按照我的需要工作,遗憾的是,这个管道函数在文档中不是很明显,所以我后来才发现它。

【讨论】:

    【解决方案2】:

    不,看read()的实现就很明显了

    def read(self, n = -1):
        """Read at most size bytes from the file
        (less if the read hits EOF before obtaining size bytes).
    
        If the size argument is negative or omitted, read all data until EOF
        is reached. The bytes are returned as a string object. An empty
        string is returned when EOF is encountered immediately.
        """
        _complain_ifclosed(self.closed)
        if self.buflist:
            self.buf += ''.join(self.buflist)
            self.buflist = []
        if n is None or n < 0:
            newpos = self.len
        else:
            newpos = min(self.pos+n, self.len)
        r = self.buf[self.pos:newpos]
        self.pos = newpos
        return r
    

    文件顶部也有这个注释

    Notes:
    - Using a real file is often faster (but less convenient).
    

    所以你最好还是使用真实文件

    【讨论】:

      猜你喜欢
      • 2010-12-09
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-04
      • 2017-06-08
      • 1970-01-01
      相关资源
      最近更新 更多