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?
我不认为不借助线程就可以以非阻塞方式使用input()。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.