Keep console input line below output

后端 未结 2 933
無奈伤痛
無奈伤痛 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...

    0 讨论(0)
  • 2021-01-19 16:37

    Your code writes everything to stdout. Whenever something arrives to either of your sender/receiver threads, it prints to stdout. The issue with that is, due to the fundamental nature of output streams, you cannot accomplish the following :

    • place incoming messages above the stuff currently being typed/echoed.

    Things happen strictly in the order of occurrence. The moment something comes in, wherever the cursor is, the print statement dumps that data over there. You cannot modify that behaviour without using fancier / more powerful constructs.

    In order to do what you want, I would use ncurses. You seem to be using python on Windows, so you're going to have to do some digging on how to get equivalent functionality. Check out this thread : Curses alternative for windows

    0 讨论(0)
提交回复
热议问题