1

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://i.stack.imgur.com/5yr3O.jpg

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"]))
  • You'll need to control your terminal so that you can print somewhere and go back to input line. [`curses`](https://docs.python.org/3.6/library/curses.html#module-curses) comes to mind. – Ondrej K. Jan 22 '19 at 00:16

1 Answers1

0

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()