[英]Python - how to print to the console while typing input?
我正在編寫一個程序,用戶需要能夠在其他任務在后台運行時輸入控制台。 問題是,每當控制台打印新行時,它都會將其附加到用戶正在輸入的行中,並且輸入會出現亂碼。
這是我寫的代碼:
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
這是我得到的 output:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.