首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python如何输出而不重写我们在多线程时输入的内容?

Python如何输出而不重写我们在多线程时输入的内容?
EN

Stack Overflow用户
提问于 2018-07-24 23:10:31
回答 1查看 0关注 0票数 0

我正在尝试使用python进行聊天,但是如果对方在我输入内容时发送文本,那就不能运行。

我的代码是这样的:

代码语言:txt
复制
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')

当我在打字的时候,然后睡眠时间到期时,它就会这样:

代码语言:txt
复制
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

虽然我希望它只在上线时输出“等待响应”,或者将我试图键入的任何内容移到“等待响应”之后。

EN

回答 1

Stack Overflow用户

发布于 2018-07-25 09:08:41

你可以使用锁定(某种程度)来实现这一点:

代码语言:txt
复制
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定期传递信息:

代码语言:txt
复制
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循环获取锁,使用它,释放它,并立即回收它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005698

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档