作为上一篇文章的扩展,不幸的是,它似乎已经死了: select.select issue for sockets and pipes。自从这篇文章以来,我一直在尝试各种无济于事的事情,我想看看是否有人知道我哪里出错了。我正在使用 select() 模块来识别管道或套接字上何时存在数据。套接字似乎工作正常,但管道被证明是有问题的。
我已按如下方式设置管道:
pipe_name = 'testpipe'
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
管道读取是:
pipein = open(pipe_name, 'r')
line = pipein.readline()[:-1]
pipein.close()
它可以作为独立的代码完美运行,但是当我尝试将其链接到 select.select 函数时,它失败了:
inputdata,outputdata,exceptions = select.select([tcpCliSock,xxxx],[],[])
我尝试在 inputdata 参数中输入 'pipe_name'、'testpipe' 和 'pipein' 但我总是收到“未定义”错误。查看其他各种帖子,我认为这可能是因为管道没有对象标识符,所以我尝试了:
pipein = os.open(pipe_name, 'r')
fo = pipein.fileno()
并将 'fo' 放在 select.select 参数中,但得到一个TypeError: an integer is required。使用“fo”的这种配置时,我也遇到了错误 9:错误的文件描述符。任何我做错的想法将不胜感激。
编辑的代码:我设法找到了解决它的方法,尽管不确定它是否特别整洁-我会对任何评论感兴趣-修改后的管道设置:
pipe_name = 'testpipe'
pipein = os.open(pipe_name, os.O_RDONLY)
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
管道阅读:
def readPipe()
line = os.read(pipein, 1094)
if not line:
return
else:
print line
监控事件的主循环:
inputdata, outputdata,exceptions = select.select([tcpCliSock,pipein],[],[])
if tcpCliSock in inputdata:
readTCP() #function and declarations not shown
if pipein in inputdata:
readPipe()
一切正常,我现在唯一的问题是在 select 进行任何事件监视之前从套接字读取代码。一旦与 TCP 服务器建立连接,就会通过套接字发送一个命令,我似乎必须等到第一次读取管道后才能通过该命令。