【问题标题】:select.select issue for sockets and pipes套接字和管道的 select.select 问题
【发布时间】:2013-09-14 03:06:58
【问题描述】:

我目前正在编写一个使用管道和套接字的基本 python 脚本。管道当前保存来自 html 表单的传入数据,套接字与服务器建立连接,该服务器以不同的时间间隔发送 TCP/IP 命令。表单和服务器在同一个局域网但不同的计算机上。

我的代码如下:

#!/usr/bin/env python
import os,sys,time
from socket import *

HOST = 'xxx.xxx.xxx.xxx'
PORT = 6000
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
count = 0
pipe_name = 'testpipe'

if not os.path.exists(pipe_name):
    os.mkfifo(pipe_name)

def readpipe():
    pipein = open(pipe_name, 'r')
    line = pipein.readline()[:-1]
    print line
    pipein.close()

def readTCP():
    data = tcpCliSock.recv(BUFSIZ)
    print data

while count == 0:
    readTCP()
    readpipe()

我意识到 count 变量当前是多余的,我一直在使用它来尝试调试一些早期的问题

如您所见,代码非常简单,只要数据首先进入管道,然后是套接字并保持这种模式,就可以正常工作。问题是它不是通过这两个函数动态运行的。它在等待套接字管道的输入时挂起。我正在尝试找到一种方法来确定管道或套接字上是否不存在数据,然后它可以关闭并检查另一个。到目前为止,我尝试过的所有操作都没有任何效果,例如检查空字符串。

我在下面的帖子中发现了一些有趣的东西,但它似乎与我正在做的事情(使用标准输入)有很大不同,所以我不确定它是否是我真正想要的,或者它是否可能是适应;

访问What's the best way to tell if a Python program has anything to read from stdin?

根据“用户”的建议,我现在整理了一些附加代码:

while True:
   inputdata,outputdata,exceptions = select.select([tcpCliSock],[],[])
   if tcpCliSock in inputdata:
      data = tcpCliSock.recv(BUFSIZ)
      print data

虽然这可行,但我无法发现将什么标识符放入管道的输入数据中。我已经阅读了 select 模块,显然它可以与管道一起使用,但它的信息似乎很少,它都是联网的东西。 我尝试了以下方法(取自上面的主要代码):

 testpipe
 pipe_name
 pipein

但我得到了各种错误,其中大部分与 NameError - 未定义TypeError: argument must be an int, or have a fileno() method

【问题讨论】:

    标签: python sockets select tcp pipe


    【解决方案1】:

    通常您会为此使用 select 模块。

    import select
    sockets_with_read_data, sockets_with_write_data, sockets_with_some_data = \
        select.select([sock, pipe], [], [], timeout = None)
    

    但我不知道这是否适用于管道。

    【讨论】:

    • 我已经导入了选择模块并在我的代码中添加了一些内容 - 请参阅上面的编辑 -
    • 还是不高兴,难道是因为我没有使用文件对象作为管道?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 2013-02-11
    • 2013-09-05
    相关资源
    最近更新 更多