Keep console input line below output

后端 未结 2 937
無奈伤痛
無奈伤痛 2021-01-19 15:55

[EDIT:] I\'m currently trying to make a small tcp chat application. Sending and receiving messages already works fine... But the problem is:

When i start typing a me

2条回答
  •  逝去的感伤
    2021-01-19 16:34

    I had a similar problem and I found that a simpler solution (for me) was to get input via readchar (https://github.com/magmax/python-readchar/tree/master/readchar).

    Using readchar, I would buffer each keystroke (checking for key.BACKSPACE and CR - see code snippet below).

    All output I would prepend with "/033[1A" (make the cursor move up), print the output line, and then a "/n"...

    after each output line, I move the cursor to the beginning and re-print the self.input_buff

    while the user is doing input, this handles console input, displaying what they are typing:

                keypress = readkey()
    
                if keypress == key.BACKSPACE:
                    self.input_buff = self.input_buff[:-1]
                    print("\033[0A%s         " % self.input_buff)
                    continue
    
                if keypress != key.CR:
                    self.input_buff = "%s%s" % (self.input_buff, keypress)
                    print("\033[0A%s" %  self.input_buff)
                    continue
    

    This kept the input line at the bottom and all terminal output above it.

    I know it comes a year late and if you are a wiz with curses, maybe that is the way to go...

提交回复
热议问题