Python 中的选择和管道问题

Aim*_*ard 5 python sockets select pipe

作为上一篇文章的扩展,不幸的是似乎已经死了: select.select issue for sockets and pipe。自从这篇文章以来,我一直在尝试各种方法都无济于事,我想看看是否有人知道我哪里出错了。我正在使用 select() 模块来识别管道或套接字上何时存在数据。套接字似乎工作正常,但管道出现问题。

我已按如下方式设置管道:

pipe_name = 'testpipe'
if not os.path.exists(pipe_name):
    os.mkfifo(pipe_name)
Run Code Online (Sandbox Code Playgroud)

和管道读取是:

pipein = open(pipe_name, 'r')
line = pipein.readline()[:-1]
pipein.close()
Run Code Online (Sandbox Code Playgroud)

它可以完美地作为独立的一段代码运行,但是当我尝试将它链接到 select.select 函数时,它失败了:

inputdata,outputdata,exceptions = select.select([tcpCliSock,xxxx],[],[])
Run Code Online (Sandbox Code Playgroud)

我尝试在 inputdata 参数中输入“pipe_name”、“testpipe”和“pipein”,但我总是收到“未定义”错误。查看其他各种帖子,我认为可能是因为管道没有对象标识符,所以我尝试了:

pipein = os.open(pipe_name, 'r')
fo = pipein.fileno()
Run Code Online (Sandbox Code Playgroud)

并将 'fo' 放在 select.select 参数中,但得到了一个TypeError: an integer is required。我也有一个错误 9:使用此 'fo' 配置时文件描述符错误。任何我做错的想法将不胜感激。

编辑代码:我设法找到了解决它的方法,尽管不确定它是否特别整洁 - 我会对任何评论感兴趣 - 修订管道设置:

pipe_name = 'testpipe'
pipein = os.open(pipe_name, os.O_RDONLY)
if not os.path.exists(pipe_name):
    os.mkfifo(pipe_name)
Run Code Online (Sandbox Code Playgroud)

管道阅读:

def readPipe()
    line = os.read(pipein, 1094)
    if not line:
        return
    else:
        print line
Run Code Online (Sandbox Code Playgroud)

监控事件的主循环:

inputdata, outputdata,exceptions = select.select([tcpCliSock,pipein],[],[])
if tcpCliSock in inputdata:
    readTCP()   #function and declarations not shown
if pipein in inputdata:
    readPipe()
Run Code Online (Sandbox Code Playgroud)

一切正常,我现在唯一的问题是在 select 的任何事件监视开始之前从套接字读取代码。一旦与 TCP 服务器建立连接,就会通过套接字发送一个命令,我似乎必须等到第一次读取管道后,才能通过该命令。

Spe*_*bun 2

根据文档, select 需要一个文件描述符 fromos.open或类似的文件描述符。所以,你应该使用select.select([pipein], [], [])作为你的命令。

或者,epoll如果您使用的是 Linux 系统,则可以使用。

poller = epoll.fromfd(pipein)
events = poller.poll()
for fileno, event in events:
  if event is select.EPOLLIN:
    print "We can read from", fileno
Run Code Online (Sandbox Code Playgroud)