Python-如何在输入时打印到控制台



我正在编写一个程序,当其他任务在后台运行时,用户需要能够在控制台中进行输入。问题是,每当控制台打印新行时,它都会将其附加到用户正在键入的行中,而输入会被打乱。

这是我写的代码:

def screen_output():
while True:
print("something")
time.sleep(1)
def user_input():
while True:
some_input = input("type in something: ")
print(f"you typed: {some_input}")
t1 = threading.Thread(target=screen_output, daemon=True)
t2 = threading.Thread(target=user_input, daemon=True)
t1.start()
t2.start()
while True:
pass

这是我得到的输出:

something
dfgdfgdfgdfgsomething
dfgdfgdfg
you typed: dfgdfgdfgdfgdfgdfgdfg
type in something: something
dfgdfgherherhsomething
erherh
you typed: dfgdfgherherherherh
type in something: erherhsomething
reherherh
you typed: erherhreherherh
type in something: erhsomething
rherherherhersomething
hztzutzusomething
ztutzasdsomething
asdasdasd
you typed: erhrherherherherhztzutzuztutzasdasdasdasd
type in something: something
asdasdasdasdassomething
d
you typed: asdasdasdasdasd
type in something: asdasdsomething
something

理想情况下,它看起来像这样:

something
you typed: dfgdfgdfgdfgdfgdfgdfg
something
you typed: dfgdfgherherherherh
something
you typed: erherhreherherh
something
something
something
something
you typed: erhrherherherherhztzutzuztutzasdasdasdasd
something
something
you typed: asdasdasdasdasd
type in something: asdasd

有什么办法解决这个问题吗?

感谢

如果您不希望输入/输出出现乱码,则必须使其按顺序排列。

使用它的一个好方法是使用Lock。线程应该在print之前和使用input之前获取该Lock,然后释放它。

这是用Lock:修改的代码

import time
import threading
iolock = threading.Lock()

def screen_output():
while True:
iolock.acquire()
print("something")
iolock.release()
time.sleep(1)

def user_input():
while True:
iolock.acquire()
some_input = input("type in something: ")
print(f"you typed: {some_input}")
iolock.release()
# Let this thread sleep as well, otherwise it
# will crowd out the other thread.
time.sleep(1)

t1 = threading.Thread(target=screen_output, daemon=True)
t2 = threading.Thread(target=user_input, daemon=True)
t1.start()
t2.start()
while True:
pass

相关内容

  • 没有找到相关文章

最新更新