【问题标题】:Simultaneous input and output using urwid使用 urwid 同时输入和输出
【发布时间】:2019-05-11 02:48:29
【问题描述】:

我正在用 Python3 编写一个服务器应用程序来同时处理和管理多个客户端连接。我需要能够向客户发送数据,同时还能立即打印他们发送的任何内容以及我的程序中的任何信息。关于此的大多数答案都建议使用 Urwid 或 Curses。我选择 urwid 主要是因为它更高级,更难搞砸。

在浏览了文档、一些教程和一些示例之后,我设法拼凑出这段代码:

import urwid

def await_command():
    return urwid.Pile([urwid.Edit(("root@localhost~# "))])

# This will actually send the command in the future and wait for a reply
def process_command(command):
    return urwid.Text(("root@localhost~# " + command + "\nCommand [" + command + "] executed successfully!"))

class CommandListBox(urwid.ListBox):
    def __init__(self):
        body = urwid.SimpleFocusListWalker([await_command()])
        super().__init__(body)

    def keypress(self, size, key):
        key = super().keypress(size, key)
        if key != 'enter': return key
        try: command = self.focus[0].edit_text
        except TypeError: return
        pos = self.focus_position
        self.body.insert(pos, process_command(command))
        self.focus_position = pos + 1
        self.focus[0].set_edit_text("")

main_screen_loop = urwid.MainLoop(CommandListBox()).run()

这主要像普通终端一样工作,除了应该可以在等待输入的当前行上方插入文本。

作为 Urwid 的新手,我不知道如何在 Python 中做到这一点。我猜它只涉及找到我们所在的行并在其上方插入一个新行。谁能提供一个如何做到这一点的例子?也欢迎对我的代码进行任何改进。

提前致谢:)

【问题讨论】:

    标签: python-3.x console urwid


    【解决方案1】:

    事实证明,这很简单。发布此内容以防有人遇到类似问题。仍然欢迎任何更正和改进。

    这就是为我做的:

    def print(self, text): # A method of the CommandListBox function
        """Insert text just above where the cursor currently is."""
        self.body.insert(self.focus_position, urwid.Text(text))
    

    这似乎仍然不是一个万无一失的方法,因为光标的位置可以改变,但它似乎到目前为止工作。

    【讨论】:

      猜你喜欢
      • 2011-09-29
      • 2020-12-12
      • 2019-08-20
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多