【问题标题】:Python readline from pipe on LinuxLinux上管道中的Python readline
【发布时间】:2011-05-31 21:28:02
【问题描述】:

当使用os.pipe() 创建管道时,它返回 2 个文件号;一个读端和一个写端,可以用os.write()/os.read()读写形式;没有 os.readline()。可以使用readline吗?

import os
readEnd, writeEnd = os.pipe()
# something somewhere writes to the pipe
firstLine = readEnd.readline() #doesn't work; os.pipe returns just fd numbers

简而言之,当你只有文件句柄号时,是否可以使用 readline?

【问题讨论】:

    标签: python pipe readline


    【解决方案1】:

    您可以使用os.fdopen() 从文件描述符中获取类似文件的对象。

    import os
    readEnd, writeEnd = os.pipe()
    readFile = os.fdopen(readEnd)
    firstLine = readFile.readline()
    

    【讨论】:

    • 完美,我知道它必须简单!
    【解决方案2】:

    将管道从os.pipe() 传递到os.fdopen(),这应该从文件描述符构建一个文件对象。

    【讨论】:

      【解决方案3】:

      听起来您想获取文件描述符(数字)并将其转换为文件对象。 fdopen 函数应该这样做:

      import os
      readEnd, writeEnd = os.pipe()
      readFile = os.fdopen(readEnd)
      # something somewhere writes to the pipe
      firstLine = readFile.readline()
      

      目前无法对此进行测试,所以如果它不起作用,请告诉我。

      【讨论】:

        【解决方案4】:

        os.pipe() 返回文件描述符,所以你必须像这样包装它们:

        readF = os.fdopen(readEnd)
        line = readF.readline()
        

        更多详情见http://docs.python.org/library/os.html#os.fdopen

        【讨论】:

          【解决方案5】:

          我知道这是一个老问题,但这里有一个不会死锁的版本。

          import os, threading
          
          def Writer(pipe, data):
              pipe.write(data)
              pipe.flush()
          
          
          readEnd, writeEnd = os.pipe()
          readFile = os.fdopen(readEnd)
          writeFile = os.fdopen(writeEnd, "w")
          
          thread = threading.Thread(target=Writer, args=(writeFile,"one line\n"))
          thread.start()
          firstLine = readFile.readline()
          print firstLine
          thread.join()
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-06-08
            • 2019-09-02
            • 1970-01-01
            • 1970-01-01
            • 2013-07-31
            • 1970-01-01
            • 2020-01-26
            • 1970-01-01
            相关资源
            最近更新 更多