简体   繁体   English

控制台中的输入文本被程序的输出分成多行

[英]Input text in the console being split into multiple lines by the output of the program

I'm currently working on a chat application with Python, but am currently facing an annoying problem.我目前正在使用 Python 开发一个聊天应用程序,但目前正面临一个烦人的问题。 When the user is inputting a message to the console, while an another user is sending messages, the input message of the first user gets split into multiple lines.当用户向控制台输入消息时,当另一个用户正在发送消息时,第一个用户的输入消息被分成多行。 I attached a picture of the problem.我附上了问题的图片。

As you can see, the input is being intercepted with the output of the console.如您所见,输入正在与控制台的输出一起被拦截。

Any idea how to prevent this?知道如何防止这种情况吗?

For the input, I was holding down Z while a friend was sending messages to the channel.对于输入,我在朋友向频道发送消息时按住 Z。 As you can see, It's being interrupted by the messages that are appearing.如您所见,它被出现的消息打断了。

Edit:编辑:

import colorama
from termcolor import cprint
colorama.init()

green = '\33[92m'
reset    = '\033[0m'

def receive_messages():
    while True:
        data = s.recv(1024).decode()
        #s is a previously defined socket
        ind = data.index(">") + 1
        usr = data[:ind]
        raw = data[ind:]
        cprint(green + usr + green + reset + raw + reset)

threading.Thread(target = receive_messages).start()

username = #opens the file where the username is stored: <username>

while True:
    txt = input()
    s.send((username + " " + txt).encode())

What I want is the input text to be locked in one line and not split into many.我想要的是将输入文本锁定在一行中而不是分成许多行。

In order to deal with this on your own you'll need to keep track of the user input character by character.为了自己处理这个问题,您需要逐个字符地跟踪用户输入。 When a message is recieved, before it's printed, erase the user input, print the incoming message, and then re-print the partially input message.收到消息后,在打印之前,擦除用户输入,打印传入消息,然后重新打印部分输入的消息。 This will make it so that the message is un-interrupted.这将使消息不被中断。

A much better idea for simplicity would be to use something like py-term or npyscreen (though I'm not sure these libraries in particular have all the features you need) in order to manage your output to the terminal which should make it so you can more easily manage where messages are printed and where the user message input is displayed in the terminal window.为简单起见,一个更好的主意是使用py-termnpyscreen 之类的东西(尽管我不确定这些库特别具有您需要的所有功能)来管理您到终端的输出,这应该使您可以更轻松地管理消息的打印位置以及用户消息输入在终端窗口中的显示位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM