等待输入时进行Python打印 [英] Python Print while waiting for input
问题描述
def receivedata(self):
while True:
data = self.soc.recv(1024)
if data != "" or data != '' or data != "":
sys.stdout.write("Recv>> ")
sys.stdout.write(data)
sys.stdout.flush()
if data == "Server Shutdown":
self.soc.close()
elif not data:
continue
def senddata(self):
while True:
try:
sys.stdout.write("Send>> ")
msg = sys.stdin.readline()
self.soc.send(msg)
except socket.error:
sys.stdout.write("Socket Connection Timed Out")
这是我的python客户端代码的一部分,因此我期望在等待用户输入的同时打印从服务器接收的内容.
This is part of my client code of python, and what I expect from this is while this waits for user input, it prints what it receives from server.
但是,客户端在等待用户输入时不打印任何内容-仅在用户输入内容后才打印.
However, client does not print anything when it is waiting for user input -- it only prints when something has been entered by user.
有没有一种方法可以更改此设置,以便即使在等待用户输入时也可以打印?
Is there a way that I could change this so that it prints even when it is waiting for user input?
推荐答案
如果您的程序需要等待2个单独的事件(用户输入和传入的套接字数据),则必须使用线程,例如:
If your program needs to wait on 2 separate events (user input and incoming socket data), you'll have to use threads, something like:
recv_thread = threading.Thread(target=receivedata)
recv_thread.setDaemon(True)
recv_thread.start()
senddata()
有关代码的事情:
- 遇到
socket.error
时,可能不是超时. - 在某一时刻,您需要从 senddata 中退出
while
循环(当用户输入特定文本时?),否则会发生异常. - 还在 receivedata 中添加异常处理 receivedata 中的
-
if
语句不正确.您可以将其替换为:
- when
socket.error
is encountered it can be something other than timeout. - at one point you will need to exit the
while
loop from senddata (when the user input a certain text? or) in case of exception. - also add exception handling in receivedata
if
statement in receivedata is not OK. you could replace it to:
if data:
...if statements...
这篇关于等待输入时进行Python打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!