Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux上来自管道的Python readline_Python_Pipe_Readline - Fatal编程技术网

Linux上来自管道的Python readline

Linux上来自管道的Python readline,python,pipe,readline,Python,Pipe,Readline,使用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 num

使用
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

您可以使用从文件描述符获取类似文件的对象

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

将管道从
os.pipe()
传递到,这将从filedescriptor构建一个文件对象。

听起来您想获取一个文件描述符(编号)并将其转换为一个文件对象。该功能应做到:

import os
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
firstLine = readFile.readline()
import os
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
# something somewhere writes to the pipe
firstLine = readFile.readline()
现在无法测试此项,因此如果它不起作用,请告诉我。

os.pipe()
返回文件描述符,因此您必须像这样包装它们:

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

有关更多详细信息,请参见

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

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()

太好了,我知道它必须很简单!