同时输出到终端时保持用户输入完整 [英] Keeping the user's input intact when outputing to terminal at the same time

查看:96
本文介绍了同时输出到终端时保持用户输入完整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为简化起见,假设我正在尝试用Python编写命令行双向聊天.我希望用户在命令提示符下使用input()输入他的消息,但是侦听线程可以随时打印消息.默认情况下,这将破坏"用户的输入.在视觉上是这样的:

To simplify, let's say I'm trying to write a command line two-way chat in Python. I would like the user to input his message with input() at the command prompt, but a listening thread could print a message at any moment. By default, this would "break" the user's input. Visually something like this:

userB>Stop interuserA wrote:Hey check this out!
rupting me!

我能找到的最接近的是此处的答案几乎是(但并非完全是)我要寻找的东西,但这确实使我指向了似乎是我所需要的blessings软件包(尽管我很满意任何软件包的答案,甚至是纯ANSII.

The closest I was able to find was this answer here which is almost, but not exactly, what I'm looking for, but it did point me towards the blessings package which seems to be what I need (although I'm happy with an answer for any package, or even pure ANSII).

我想要实现的是从用户输入的上方线程中打印输入的输出,以使他的文本不会中断.假设用户正在输入:

What I'm trying to achieve is to print incoming output from a Thread above the user's input, so that his text doesn't break. Let's say the user is typing:

userB>Stop inter

突然有消息从线程中发出,但是我们用户的输入没有停止:

Suddenly a message comes in from the thread, but our user's input doesn't brake:

userA says: Ok I won't interrupt you
userB>Stop inter

我的线程理论上的print_incoming_message()方法应如何实现?

What should my threads theoretical print_incoming_message() method look like to achieve this?

NB:我正在使用Linux,并且对跨平台兼容性不感兴趣.

NB: I'm using Linux and am not interested in cross-platform compatibility.

推荐答案

有两种方法.

一种是使用ncurses.为此有python绑定.使用ncurses,可以完全控制终端屏幕,并且可以随时打印字符.

One is to use ncurses. There are python bindings for this. With ncurses, the terminal screen is under your complete control, and you can print characters at any point.

如果没有ncurses,则不能在当前行上方书写.但是,您可以进行的操作是打印一个\r字符并返回到该行的开头.

Without ncurses, you can't write above the current line. What you can do, however, is print a \r character and go back to the beginning of the line.

如果保存用户的输入(例如,他写了foo),并且要在其上打印行bar,则可以输出:

If you save the user's input (say he wrote foo), and you want to print the line bar above that, you can output:

\rbar\nfoo

这将覆盖当前行,并引入换行符,从而将用户的输入下移.效果类似,但不会像ncurses那样防篡改.

This will overwrite the current line, and introduce a newline, moving the user's input down. The effect is similar, but it won't be as tamper-proof as ncurses.

这篇关于同时输出到终端时保持用户输入完整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆