簡體   English   中英

Python線程-將輸入優先於輸出

[英]Python Threading - Prioritising Input Over Output

我有一個python程序,該程序使用套接字在網絡上發送消息,該套接字使用兩個線程,一個線程運行服務器,一個線程運行客戶端。 但是,如果在用戶部分輸入內容時接收到消息,則接收到的消息會在兩半輸入之間打印。 盡管這在功能上沒有什么區別,但從美學上看,這太可怕了。 有什么辦法可以使該消息輸出,就像在用戶開始鍵入之前收到消息一樣?

如果我的解釋不清楚,假設用戶在收到消息(“ Sup”)之前輸入“ hel”,然后在收到“ lo”之后輸入“ lo”,則將顯示:

HelPartner Sent: Sup
lo

任何建議都將受到歡迎。

認為您可以使用readline做到這一點。

當然,這意味着它在Windows上將無濟於事。 或者,如果您對sys.stdin做過一些時髦的sys.stdin ,或者直接從stdin讀取而不是使用諸如input函數,或者您不在TTY上,或者您正在像IDLE這樣的環境中運行,該環境會鈎住input但是以其他方式都不是破壞交易的前提, readline.get_line_buffer()可能就是您想要的。

如果您希望將輸出排隊,直到用戶完成輸入為止(基本上與外殼程序執行的操作(例如作業控制消息)相同),如下所示:

import readline
output_buffer = []
output_buffer_lock = threading.Lock()

# Wherever you would normally print the output
if readline.get_line_buffer():
    with output_buffer_lock:
        output_buffer.append(output)
else:
    with output_buffer_lock:
        print('\n'.join(output_buffer + [output]))
        output_buffer = []

# Wherever you're reading the input
line = input()
with output_buffer_lock:
    print('\n'.join(output_buffer + [output]))
    output_buffer = []

如果您想打斷用戶的輸入,請記住他們鍵入的內容,顯示輸出,然后重新啟動輸入,這有點復雜。 輸出線程將需要某種方式來存放當前輸入緩沖區( readline.get_line_buffer ),中斷輸入線程,清除當前輸入(先打印'\\r' then a row of spaces and another '\\r' should do it in simple cases, but see below), print the output, start a new輸入call, and refill the buffer ( readline.insert_text then possibly readline.redisplay ; note that you have to call this after輸入starts but before it returns, so you probably want to use ; note that you have to call this after starts but before it returns, so you probably want to use set_pre_input_hook`來執行此操作)。

如果輸入發生在主線程上,則signal處理程序(只會引發自定義異常)是中斷input調用的好方法。 如果沒有,那就麻煩得多了。

同時, readline支持多行輸入,並且默認情況下,如果用戶鍵入80個以上(或$COLS )字符,則將內容包裝到多行中。 在那種情況下,實際上沒有辦法從Python的readline模塊提供的高級API中擦除整個輸入。 除非您要編寫或查找帶有ctypes或自定義擴展模塊的低級包裝,否則無法找到解決此問題的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM