gpt4 book ai didi

python - 启动通过套接字编程处理 HTTP 请求的 python 脚本时,CPU 达到 100%?

转载 作者:可可西里 更新时间:2023-11-01 17:05:38 26 4
gpt4 key购买 nike

我正在编写一个脚本,用于通过套接字编程处理 HTTP 请求。我的 Python 脚本只读取每个 HTTP 响应,搜索几个关键字并增加计数器。

当没有传入消息时,仅启动脚本会占用 CPU 高达 90-99%。我该如何处理?

HOST = '' 
SOCKET_LIST = []
RECV_BUFFER = 40966
PORT=int(sys.argv[1])
serviceInitiatedEvent=0
deliveredEvent=0
EstablishedEvent=0
ConnectionClearedEvent=0

def chat_server():

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)

SOCKET_LIST.append(server_socket)

print "Chat server started on port " + str(PORT)

try:
while 1:

ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)

for sock in ready_to_read:
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)


else:
try:
data = sock.recv(RECV_BUFFER)
if data:
if re.search('serviceInitiatedEvent></SOAP-ENV',data):
global serviceInitiatedEvent
serviceInitiatedEvent+=1
if re.search('deliveredEvent></SOAP-ENV',data):
global deliveredEvent
deliveredEvent+=1

else:

if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)

except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue

except KeyboardInterrupt:
print "service Initiated Event:%s" % (serviceInitiatedEvent)
print "delivered Event: %s" % (deliveredEvent)


server_socket.close()



if __name__ == "__main__":

sys.exit(chat_server())

最佳答案

如果您的代码中 while 1 循环利用了 100%,那可能就是罪魁祸首。它叫做busy waiting .

select函数有 timeout 参数指定它应该等待事件多长时间。在您的代码中,您将其设置为 0,这样当套接字中没有可用数据时,控制会立即返回,从而导致繁忙的等待循环。

根据您的需要指定一些更大的超时,以便您的代码在无事可做时不会旋转:

ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[], 1)
# ^^^ here

关于python - 启动通过套接字编程处理 HTTP 请求的 python 脚本时,CPU 达到 100%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45564478/

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