我正在使用相同的代码进行Socket编程和pexpect的组合。我有它的工作,但有一个小故障。 select API在第一次迭代中等待指定的5秒。一旦收到来自客户端的输入,即使在循环中指定了它,它也不再等待5秒。在第一次客户端服务器交互发生后,选择无效!我理解如何在C ++中绕过这一点,但我对Python比较新,我无法弄清楚原因。我附上了下面的代码,非常简单。
#!/usr/bin/python
#Basic Functionailty: to create a process and to take inputs from client machines
#This input will be given to a background process which will display the user the parsed output
#using pexpect
import pexpect
import socket
import select
TCP_IP = '127.0.0.1'
TCP_PORT = 50050
BUFFER_SIZE = 1024
#spawning a pexpect process and printing everything before the prompt appears
child = pexpect.spawn('./pox.py')
child.expect ('POX>')
print child.before
#binding to a port number and acting as a server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((TCP_IP, TCP_PORT))
server.listen(1)
input = [server]
#loop infinitely and get input and serve it to the process
#in addition to which if the process shows some messages display
#it to the user
while 1:
print 'Before select'
inputready,outputready,exceptready = select.select(input,[],[],5)
for s in inputready:
if s == server:
#if the input is from the server
conn, addr = s.accept()
print 'Connection address:', addr
input.append(conn)
data = conn.recv(BUFFER_SIZE)
if not data: continue
print "received data:", data
child.sendline (data)
else:
#if a time out occurs check the pexpect if it has any debug messages
i = child.expect ([pexpect.TIMEOUT, 'POX>'], timeout=1)
print child.before
if i == 0:
print child.before
答案 0 :(得分:1)
您修改了input
:
input.append(conn)
(然后调用conn.recv
来获取一些数据,这些数据会阻塞直到有一些数据或EOF,但可能会有一些数据或你得到它。
完成此操作后,在下一次循环中,很可能 接收数据或EOF,准备好在conn
上输入。我假设您立即致电child.expect
(因为s == conn
因此s != server
)。我敢打赌,在这一点上,conn
处于EOF,因此在没有做任何事情的情况下立即返回。 conn
仍处于input
状态,因此每当您致电select
时,它都会立即返回,告诉您可以从conn
读取另一个EOF。