IRC客户端应用程序,如何在python中使用select()

时间:2014-10-22 14:29:16

标签: python multithreading select

您正在处理从标准输入读取的网络应用程序,并在无限循环中将消息发送到服务器。对于我有线程的每个循环,调用函数应该做什么。我需要能够捕获SIGINT并正确关闭两个线程。我的程序都依赖于两种阅读功能。我想我应该使用select()函数,但我不知道如何。

def writing_mode():
    while 1:
        var = raw_input()
        # some options with what to do with the var

def listening_mode():
    readbuffer = ""

    while 1:
        readbuffer = readbuffer + s.recv(1024)
        temp = string.split(readbuffer, "\r\n")
        readbuffer = temp.pop()

        for line in temp:
            line = string.strip(line)
            prefix, command, rest, trailing = parse(line)

            # do something with the options u have

s=socket.socket()
try:
    s.connect((args.h, args.p))
except Exception, e:
    print("Something is wrong with %s:%d, Exception type is:\n%s" % (args.h, args.p, e))
    sys.exit()

s.send("NICK AAA\r\n")
s.send("USER AAA AAA AAA AAA\r\n")

thread.start_new_thread(writing_mode)
thread.start_new_thread(listenning_mode)
#main program waiting for signals

1 个答案:

答案 0 :(得分:0)

我通过select()非阻塞读取解决了这个问题。

while condition:
    # s is socket to read from
    # for stdin use sys.stdin instead
    ready = select.select([s], [], [], 0)
    if ready[0]:
        #u can start read

选择功能,只有在有任何要阅读的内容时才会继续读取功能。否则它会进入while循环,因此条件可以随时停止。