小编Han*_*nif的帖子

Python如何打印而不会覆盖我们在多线程时输入的内容

我正在尝试使用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')
Run Code Online (Sandbox Code Playgroud)

当我在打字中间,然后睡眠时间到期时,它就像这样搞砸了:

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 …
Run Code Online (Sandbox Code Playgroud)

python code-formatting python-3.x

5
推荐指数
0
解决办法
81
查看次数

标签 统计

code-formatting ×1

python ×1

python-3.x ×1