简体   繁体   English

如何将 Rich 与 Python 诅咒集成?

[英]How to integrate Rich with Python curses?

I'm thinking of creating a CLI app using python curses and rich libraries.我正在考虑使用 python cursesrich库创建一个 CLI 应用程序。 As curses requires addstr method to print text to string, I'm unable to print using rich .由于curses需要addstr方法将文本打印为字符串,因此我无法使用rich进行打印。 Is it possible to integrate these two libraries?是否可以整合这两个库?

Following codes don't work accordingly!!以下代码不相应地工作!

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)

Author of Rich here. Rich 的作者在这里。 Rich and Curses probably aren't going to work well in combination. Rich 和 Curses 可能无法很好地结合使用。 However you could look in to Textual which is a TUI framework I'm working on that uses Rich under the hood.但是,您可以查看Textual ,这是我正在研究的一个 TUI 框架,它在底层使用 Rich。

It seems you want to pipe the content from rich to curses but the print() function is not actually returning anything it is simply creating output on the terminal as a side effect of executing.看起来你想要 pipe 从richcurses的内容,但是print() function 实际上并没有返回任何东西它只是在终端上创建 output 作为执行的副作用。

You can verify by looking at type(print("[red]Hello[/red] World!")) which is <class 'NoneType'> .您可以通过查看type(print("[red]Hello[/red] World!"))<class 'NoneType'>

So, how can you retrieve the output from the print(...) ?那么,如何从print(...)中检索 output 呢? In the docs for rich they explain how this can be done with the Console API: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'>

Which allows you to access the output from the print and you can then try to pipe that information to curses.这允许您从 print 访问 output,然后您可以尝试 pipe 将该信息诅咒。 You may run into some strange interferences from mixing curses and rich if you are overlapping their color contexts because of how color escape codes work in shells so be aware of that.由于颜色转义码在 shell 中的工作方式,如果你重叠它们的颜色上下文,你可能会遇到混合cursesrich的一些奇怪的干扰,所以要注意这一点。

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

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