【发布时间】: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