[英]Print and input at the same time python multithread
I want to build chat-like application. 我想构建类似聊天的应用程序。 I have two threads, one for user input and one for printing received messages.
我有两个线程,一个用于用户输入,一个用于打印收到的消息。 When socket receives the message it prints it out but it ruins user input.
当套接字收到消息时,它会打印出来,但会破坏用户输入。 I want to know if there is any way for print to skip input line.
我想知道是否可以通过任何方式跳过输入行。
https://imgur.com/ZlTIIqT https://imgur.com/ZlTIIqT
You can see how it removes ">>" when client connects. 您可以看到客户端连接时如何删除“ >>”。 I just want print and input at the same time without disrupting input.
我只想同时打印和输入而不中断输入。
PRINT 打印
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 })
INPUT 输入
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"]))
I found solution with curses. 我找到了解决诅咒的方法。 Here is the code if someone finds it useful.
如果有人觉得有用,请参见以下代码。
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.