[英]how to prompt for user input without blocking in python3?
我正在尝试对要从客户端发送到服务器的命令进行类型检查。 我想使用select,所以我不会阻塞任何东西,但是如果我公然要求input()
,则会阻塞。 因此,似乎我应该改用sys.stdin.readline()
。 但是,在输入的命令和我要执行的类型检查之间没有连接:
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()
基本上,如果客户端无法将接收到的数据识别为命令,则客户端将其视为只是聊天消息,并将其相应地写入stdout。 但是,当我收到类似'GO'
的命令时,我需要客户端提示(或仅显示一条询问输入的消息,这样我就不会阻塞input()
),以便用户输入命令,以便可以对命令进行类型检查。命令在同一巢中。 没有线程,这可能吗?
我不认为不借助线程就可以以非阻塞方式使用input()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.