我正在同一代码中结合使用 Socket 编程和 pexpect。我已经让它工作了,但有一个小故障。选择 API 在第一次迭代中等待指定的 5 秒。一旦它收到来自客户端的输入,它就不再等待 5 秒,即使它是在循环中指定的。简而言之,在第一次客户端服务器交互发生后,select 没有任何效果!我了解如何在 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