[英]How to integrate Rich with Python curses?
I'm thinking of creating a CLI app using python curses
and rich
libraries.我正在考虑使用 python
curses
和rich
库创建一个 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)
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 从
rich
到curses
的内容,但是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 中的工作方式,如果你重叠它们的颜色上下文,你可能会遇到混合
curses
和rich
的一些奇怪的干扰,所以要注意这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.