我在python中有一个select的问题,我有一段代码允许客户端从服务器接收数据,并通过读取stdin并在服务器套接字上写入来发送数据:
readfds = [s, sys.stdin]
writefds = [s, sys.stdout]
my_level = get_my_level(s)
is_co = True
cmd = ""
while (is_co):
read, write, exception = select.select(readfds, writefds, [], 1)
if (not (read or write or exception)):
print "Timeout"
else:
for sock in read:
if (sock == s):
cmd = readline(s)
print cmd
elif (sock == sys.stdin):
cmd = sys.stdin.readline()
s.sendall(cmd)
if (cmd == "mort"):
is_co = False
我想这是因为select是非阻塞的,但是当我让它阻塞时,它是一样的。你能解释一下我的代码有什么错误吗?在
谢谢
假设您总是可以写入
sys.stdout
,因此select.select
应该立即返回,让您知道您可以写入某些内容。然后,该代码处理可读列表,然后重新进入循环。但是对于sys.stdout
没有任何变化,因此它仍然是可写的。在这将在一个紧密的循环中执行并消耗CPU。在
我也有类似的问题,所以我不断地轮询套接字(在我的例子中是UDP)并使用sleep()超时。在这段代码中,CPU使用率从100%增加到4%
相关问题 更多 >
编程相关推荐