gpt4 book ai didi

python - select.select 套接字和管道问题

转载 作者:可可西里 更新时间:2023-11-01 02:54:42 25 4
gpt4 key购买 nike

我目前正在编写一个同时使用管道和套接字的基本 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 - not definedTypeError: argument must be an int, or have a fileno() method相关/p>

最佳答案

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

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

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

关于python - select.select 套接字和管道问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18718355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com