簡體   English   中英

同時打印和輸入python多線程

[英]Print and input at the same time python multithread

我想構建類似聊天的應用程序。 我有兩個線程,一個用於用戶輸入,一個用於打印收到的消息。 當套接字收到消息時,它會打印出來,但會破壞用戶輸入。 我想知道是否可以通過任何方式跳過輸入行。

https://imgur.com/ZlTIIqT

您可以看到客戶端連接時如何刪除“ >>”。 我只想同時打印和輸入而不中斷輸入。

打印

def listen_clients(self):
    while True:
        conn, addr = self.sock.accept()
        print(clr("[+] Client connected ({}:{})".format(addr[0], addr[1]), "green"))
        self.clients.append({
            "ip": addr[0],
            "port": addr[1],
            "conn": conn })

輸入

def initiate_cli(self):
    while True:
        command = input(" >> ")
        if command == "clients":
            for client in self.clients:
                print("  {0:3}: {1}: {2:5}".format(self.clients.index(client), client["ip"], client["port"]))

我找到了解決詛咒的方法。 如果有人覺得有用,請參見以下代碼。

import curses

history = []
def pprint(text):
    global history
    history.insert(0, text)
    if len(history) == int(curses.LINES) - 2:
        history = history[:int(curses.LINES) - 3]
    quote_window.clear()
    for his in history[::-1]:
        quote_window.addstr(his + "\n")
        quote_window.refresh()

stdscr = curses.initscr()

curses.noecho()
curses.cbreak()
stdscr.keypad(True)
curses.curs_set(0)

if curses.has_colors():
    curses.start_color()

curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)

stdscr.addstr("Server", curses.A_REVERSE)
stdscr.chgat(-1, curses.A_REVERSE)

quote_window = curses.newwin(curses.LINES-2, curses.COLS, 1, 0)
input_window = curses.newwin(curses.LINES, curses.COLS, curses.LINES-1, 0)
input_window.bkgd(curses.color_pair(1))
input_window.addstr(">> ")
stdscr.noutrefresh()
quote_window.noutrefresh()
input_window.noutrefresh()

curses.doupdate()

comm = ""
while True:
    key = input_window.getch()
    if key == 10:
        pprint(comm)
        input_window.clear()
        input_window.addstr(">> ")
        comm = ""
    else:
        input_window.addstr(chr(key))
        comm += chr(key)

curses.nocbreak()
curses.echo()
curses.curs_set(1)
curses.endwin()

暫無
暫無

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

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