我正在尝试使用python进行聊天,但是如果对方在我输入内容时发送文本,那就不能运行。
我的代码是这样的:
import threading
import time
import sys
def printf(str, *args):
print(str % args, end='')
def printwait():
global End
while not End:
time.sleep(3)
print(' ')
print('waiting respond')
def reqinput():
global End
while not End:
name = input("Input your name:")
End=name=='@end'
End=False
t1=threading.Thread(target=printwait)
t2=threading.Thread(target=reqinput)
t1.start()
t2.start()
t1.join()
t2.join()
print('done')
当我在打字的时候,然后睡眠时间到期时,它就会这样:
Input your name:waiting respond
im trying twaiting respond
o typwaiting respond
e somethingwaiting respond
here
Input your name:waiting respond
waiting respond
waiting respond
waiting respond
waiting respond
waiting respond
waiting respond
@waiting respond
end
waiting respond
done
虽然我希望它只在上线时输出“等待响应”,或者将我试图键入的任何内容移到“等待响应”之后。
发布于 2018-07-25 09:08:41
你可以使用锁定(某种程度)来实现这一点:
import threading
import time
import sys
printLock = threading.Lock()
def printf(str, *args):
print(str % args, end='')
def printwait():
global End
while not End:
time.sleep(3)
with printLock:
print(' ')
print('waiting respond')
def reqinput():
global End
while not End:
with printLock:
name = input("Input your name:")
End=name=='@end'
End=False
t1=threading.Thread(target=printwait)
t2=threading.Thread(target=reqinput)
# start both threads and join them in a single
# call so the input() call doesn't interrupt us.
threads = [t1.start(), t2.start(), t1.join(), t2.join()]
注意,在没有睡眠的情况下,reqinput
方法,有时我看不到waiting respond
定期传递信息:
Input your name:test
Input your name:test2
waiting respond
Input your name:test6
Input your name:test6
Input your name:test8
Input your name:test8
Input your name:@end
waiting respond
发生这种情况是因为reqinput循环获取锁,使用它,释放它,并立即回收它。
https://stackoverflow.com/questions/-100005698
复制相似问题