繁体   English   中英

如何将 Rich 与 Python 诅咒集成?

[英]How to integrate Rich with Python curses?

我正在考虑使用 python cursesrich库创建一个 CLI 应用程序。 由于curses需要addstr方法将文本打印为字符串,因此我无法使用rich进行打印。 是否可以整合这两个库?

以下代码不相应地工作!

import curses
from curses import wrapper
from rich.console import Console
console = Console()
with console.capture() as capture:
    console.print("[bold red]Hello[/] World")
str_output = capture.get()

def main(stdscr):
    stdscr.clear()
    stdscr.addstr(str_output)
    stdscr.refresh()
    stdscr.getch()

wrapper(main)

Rich 的作者在这里。 Rich 和 Curses 可能无法很好地结合使用。 但是,您可以查看Textual ,这是我正在研究的一个 TUI 框架,它在底层使用 Rich。

看起来你想要 pipe 从richcurses的内容,但是print() function 实际上并没有返回任何东西它只是在终端上创建 output 作为执行的副作用。

您可以通过查看type(print("[red]Hello[/red] World!"))<class 'NoneType'>

那么,如何从print(...)中检索 output 呢? rich 的文档中,他们解释了如何使用控制台 API 完成此操作:

from rich.console import Console
console = Console()
with console.capture() as capture:
    console.print("[bold red]Hello[/] World")

str_output = capture.get()


>>> str_output
'\x1b[1;31mHello\x1b[0m World\n'
>>> print(str_output)
Hello World

>>> type(str_output)
<class 'str'>

这允许您从 print 访问 output,然后您可以尝试 pipe 将该信息诅咒。 由于颜色转义码在 shell 中的工作方式,如果你重叠它们的颜色上下文,你可能会遇到混合cursesrich的一些奇怪的干扰,所以要注意这一点。

暂无
暂无

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

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