开发者

how to prompt for user input without blocking in python3?

I'm trying to type-check the commands I want to send to a server from a client. I want to use select so I don't block anything, but if I blatantly ask for input(), I block. So, it seems I should use sys.stdin.readline() instead. However, then there is a disconnect between the commands entered and the type checking I want to do:

while not self.flag:
    sock_read, sock_write, sock_except = \
        select.select([sys.stdin, self.client], [], [])

    for sock in sock_read:
        if sock == sys.stdin:
            data = sys.stdin.readline().strip()
            if data:
                self.client.send(data.encode('utf_8'))
        elif sock == self.client:
            data = sock.recv(bufsize)
            if data.decode('utf_8') is '':  # server closed connection
                print("Lost connection to server, shutting down...")
                self.flag = True
                break
            else:   # process data '\n' delimited
                readbuf += data
                while b'\n' in readbuf:
                    msg,readbuf = readbuf.split(b'\n', 1) # separate by \n
                    msg = msg.decode('utf_8')
                    msg.strip('\n')
                    # make below into a function
                    # got data from server
                    if msg == 'BEGIN':
                        self.playstarted = True
                    elif msg == 'GO':
                        #command = input("Your turn: ")
                        # typecheck command, something like
                        # while is_not_valid_command():
                        #   keep asking for input
                        print("You",command)

                        command += '\n' # delimiter
                        sock.send(command.encode('utf_8'))
                    else:
                        sys.stdout.write(msg + "\n")
                        sys.stdout.flush()

Basically, if the client does not recognize the received data as a command, the client assumes it is just a chat message and writes it to stdout accordingly. But, when I get a command like 'GO', I need the client to prompt (or just display a message asking开发者_如何学编程 for input so I don't block with input()) the user for command input so I can type-check the command within the same nest. Is this possible without threads?


I don't think it is possible to use input() in a non-blocking way without resorting to threads.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜