我正在编写一个程序,当其他任务在后台运行时,用户需要能够输入控制台。问题是,每当控制台打印新行时,它会将其附加到用户键入的行,并且输入会出现乱码。
这是我写的代码:
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
。
线程应该在 Lock
之前和使用 print
之前获取 input
并在之后释放它。
这是用
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
我有一个想法,你可以做什么:将打印空间和控制台输入空间分开,你可以使用 ANSI 转义码将光标向上移动一行并移动到行尾,打印换行符 和消息,有点像消息应用程序的界面。我以前没有尝试过这个,但它可以工作。 尝试后我会编辑此回复。