标签归档:markdown

在Markdown和reStructuredText中都具有相同的自述文件

问题:在Markdown和reStructuredText中都具有相同的自述文件

我有一个托管在GitHub上的项目。为此,我使用Markdown语法编写了自述文件,以便在GitHub上很好地格式化它。

由于我的项目使用Python,因此我还计划将其上传到PyPi。PyPi上用于README的语法为reStructuredText。

我希望避免处理两个包含大致相同内容的自述文件。因此,我搜索了RST(或相反)转换器的降价促销,但找不到任何商品。

我看到的另一个解决方案是执行markdown / HTML,然后执行HTML / RST转换。我在这里这里都找到了一些资源,所以我猜应该是可行的。

您有什么想法可以更好地适合我的工作吗?

I have a project hosted on GitHub. For this I have written my README using the Markdown syntax in order to have it nicely formatted on GitHub.

As my project is in Python I also plan to upload it to PyPi. The syntax used for READMEs on PyPi is reStructuredText.

I would like to avoid having to handle two READMEs containing roughly the same content; so I searched for a markdown to RST (or the other way around) translator, but couldn’t find any.

The other solution I see is to perform a markdown/HTML and then a HTML/RST translation. I found some ressources for this here and here so I guess it should be possible.

Would you have any idea that could fit better with what I want to do?


回答 0

我会推荐Pandoc,“将文件从一种标记格式转换为另一种格式的瑞士军刀”(在页面底部查看受支持的转换图,这是非常令人印象深刻的)。Pandoc允许markdown直接进行reStructuredText翻译。此外,还有一个在线编辑器,在这里它可以让你尝试一下,所以你可以简单地使用在线编辑器来转换你的自述文件。

I would recommend Pandoc, the “swiss-army knife for converting files from one markup format into another” (check out the diagram of supported conversions at the bottom of the page, it is quite impressive). Pandoc allows markdown to reStructuredText translation directly. There is also an online editor here which lets you try it out, so you could simply use the online editor to convert your README files.


回答 1

正如@Chris建议的那样,您可以使用Pandoc将Markdown转换为RST。这可以使用pypandoc模块和setup.py中的一些魔术来简单地自动化:

from setuptools import setup
try:
    from pypandoc import convert
    read_md = lambda f: convert(f, 'rst')
except ImportError:
    print("warning: pypandoc module not found, could not convert Markdown to RST")
    read_md = lambda f: open(f, 'r').read()

setup(
    # name, version, ...
    long_description=read_md('README.md'),
    install_requires=[]
)

对于在PyPi上使用的详细说明,这将自动将README.md转换为RST。当pypandoc不可用时,它将仅读取README.md而不进行转换-不会在其他人只想构建模块而不上传到PyPi时不强迫其他人安装pypandoc。

因此,您可以像往常一样在Markdown中编写内容,而不再关心RST混乱了。;)

As @Chris suggested, you can use Pandoc to convert Markdown to RST. This can be simply automated using pypandoc module and some magic in setup.py:

from setuptools import setup
try:
    from pypandoc import convert
    read_md = lambda f: convert(f, 'rst')
except ImportError:
    print("warning: pypandoc module not found, could not convert Markdown to RST")
    read_md = lambda f: open(f, 'r').read()

setup(
    # name, version, ...
    long_description=read_md('README.md'),
    install_requires=[]
)

This will automatically convert README.md to RST for the long description using on PyPi. When pypandoc is not available, then it just reads README.md without the conversion – to not force others to install pypandoc when they wanna just build the module, not upload to PyPi.

So you can write in Markdown as usual and don’t care about RST mess anymore. ;)


回答 2

2019更新

PyPI Warehouse 现在也支持渲染Markdown!您只需要更新软件包配置并将其添加long_description_content_type='text/markdown'到其中即可。例如:

setup(
    name='an_example_package',
    # other arguments omitted
    long_description=long_description,
    long_description_content_type='text/markdown'
)

因此,无需再将README保留为两种格式。

您可以在文档中找到有关它的更多信息。

旧答案:

GitHub使用的标记库支持reStructuredText。这意味着您可以编写README.rst文件。

它们甚至使用codecode-block指令支持语法特定的颜色突出显示(示例

2019 Update

The PyPI Warehouse now supports rendering Markdown as well! You just need to update your package configuration and add the long_description_content_type='text/markdown' to it. e.g.:

setup(
    name='an_example_package',
    # other arguments omitted
    long_description=long_description,
    long_description_content_type='text/markdown'
)

Therefore, there is no need to keep the README in two formats any longer.

You can find more information about it in the documentation.

Old answer:

The Markup library used by GitHub supports reStructuredText. This means you can write a README.rst file.

They even support syntax specific color highlighting using the code and code-block directives (Example)


回答 3

PyPI现在支持Markdown进行详细描述!

在中setup.py,设置long_description为Markdown字符串,添加long_description_content_type="text/markdown"并确保您使用的是最新工具(setuptools38.6.0 +,twine1.11 +)。

有关更多详细信息,请参见Dustin Ingram的博客文章

PyPI now supports Markdown for long descriptions!

In setup.py, set long_description to a Markdown string, add long_description_content_type="text/markdown" and make sure you’re using recent tooling (setuptools 38.6.0+, twine 1.11+).

See Dustin Ingram’s blog post for more details.


回答 4

根据我的要求,我不想在计算机上安装Pandoc。我用了docverter。Docverter是具有HTTP接口的文档转换服务器,为此使用了Pandoc。

import requests
r = requests.post(url='http://c.docverter.com/convert',
                  data={'to':'rst','from':'markdown'},
                  files={'input_files[]':open('README.md','rb')})
if r.ok:
    print r.content

For my requirements I didn’t want to install Pandoc in my computer. I used docverter. Docverter is a document conversion server with an HTTP interface using Pandoc for this.

import requests
r = requests.post(url='http://c.docverter.com/convert',
                  data={'to':'rst','from':'markdown'},
                  files={'input_files[]':open('README.md','rb')})
if r.ok:
    print r.content

回答 5

您可能还对以下事实感兴趣:可以编写一个公共子集,以便在以markdown呈现或以reStructuredText呈现时,文档以相同的方式出现:https: //gist.github.com/dupuy/1855764☺

You might also be interested in the fact that it is possible to write in a common subset so that your document comes out the same way when rendered as markdown or rendered as reStructuredText: https://gist.github.com/dupuy/1855764


回答 6

我遇到了这个问题,并使用以下两个bash脚本解决了这个问题。

请注意,我已将LaTeX捆绑到Markdown中。

#!/usr/bin/env bash

if [ $# -lt 1 ]; then
  echo "$0 file.md"
  exit;
fi

filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"

if [ "$extension" = "md" ]; then
  rst=".rst"
  pandoc $1 -o $filename$rst
fi

将其转换为html也很有用。md2html:

#!/usr/bin/env bash

if [ $# -lt 1 ]; then
  echo "$0 file.md <style.css>"
  exit;
fi

filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"

if [ "$extension" = "md" ]; then
  html=".html"
  if [ -z $2 ]; then
    # if no css
    pandoc -s -S --mathjax --highlight-style pygments $1 -o $filename$html
  else
    pandoc -s -S --mathjax --highlight-style pygments -c $2 $1 -o $filename$html
  fi
fi

希望对您有所帮助

I ran into this problem and solved it with the two following bash scripts.

Note that I have LaTeX bundled into my Markdown.

#!/usr/bin/env bash

if [ $# -lt 1 ]; then
  echo "$0 file.md"
  exit;
fi

filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"

if [ "$extension" = "md" ]; then
  rst=".rst"
  pandoc $1 -o $filename$rst
fi

Its also useful to convert to html. md2html:

#!/usr/bin/env bash

if [ $# -lt 1 ]; then
  echo "$0 file.md <style.css>"
  exit;
fi

filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"

if [ "$extension" = "md" ]; then
  html=".html"
  if [ -z $2 ]; then
    # if no css
    pandoc -s -S --mathjax --highlight-style pygments $1 -o $filename$html
  else
    pandoc -s -S --mathjax --highlight-style pygments -c $2 $1 -o $filename$html
  fi
fi

I hope that helps


回答 7

使用pandoc其他人建议的工具,我创建了一个md2rst实用程序来创建rst文件。即使此解决方案意味着您同时拥有an md和an,rst但它似乎是侵入性最小的,并且将允许将来添加任何降价支持。与更改相比setup.py,我更喜欢它,也许您也会:

#!/usr/bin/env python

'''
Recursively and destructively creates a .rst file for all Markdown
files in the target directory and below.

Created to deal with PyPa without changing anything in setup based on
the idea that getting proper Markdown support later is worth waiting
for rather than forcing a pandoc dependency in sample packages and such.

Vote for
(https://bitbucket.org/pypa/pypi/issue/148/support-markdown-for-readmes)

'''

import sys, os, re

markdown_sufs = ('.md','.markdown','.mkd')
markdown_regx = '\.(md|markdown|mkd)$'

target = '.'
if len(sys.argv) >= 2: target = sys.argv[1]

md_files = []
for root, dirnames, filenames in os.walk(target):
    for name in filenames:
        if name.endswith(markdown_sufs):
            md_files.append(os.path.join(root, name))

for md in md_files:
    bare = re.sub(markdown_regx,'',md)
    cmd='pandoc --from=markdown --to=rst "{}" -o "{}.rst"'
    print(cmd.format(md,bare))
    os.system(cmd.format(md,bare))

Using the pandoc tool suggested by others I created a md2rst utility to create the rst files. Even though this solution means you have both an md and an rst it seemed to be the least invasive and would allow for whatever future markdown support is added. I prefer it over altering setup.py and maybe you would as well:

#!/usr/bin/env python

'''
Recursively and destructively creates a .rst file for all Markdown
files in the target directory and below.

Created to deal with PyPa without changing anything in setup based on
the idea that getting proper Markdown support later is worth waiting
for rather than forcing a pandoc dependency in sample packages and such.

Vote for
(https://bitbucket.org/pypa/pypi/issue/148/support-markdown-for-readmes)

'''

import sys, os, re

markdown_sufs = ('.md','.markdown','.mkd')
markdown_regx = '\.(md|markdown|mkd)$'

target = '.'
if len(sys.argv) >= 2: target = sys.argv[1]

md_files = []
for root, dirnames, filenames in os.walk(target):
    for name in filenames:
        if name.endswith(markdown_sufs):
            md_files.append(os.path.join(root, name))

for md in md_files:
    bare = re.sub(markdown_regx,'',md)
    cmd='pandoc --from=markdown --to=rst "{}" -o "{}.rst"'
    print(cmd.format(md,bare))
    os.system(cmd.format(md,bare))

将Sphinx与Markdown而不是RST一起使用

问题:将Sphinx与Markdown而不是RST一起使用

我讨厌RST,但喜欢狮身人面像。有没有一种方法可以让狮身人面像读取markdown而不是reStructuredText?

I hate RST but love sphinx. Is there a way that sphinx reads markdown instead of reStructuredText?


回答 0

做到这一点的“正确”方法是为降价编写docutils解析器。(加上一个Sphinx选项来选择解析器。)它的优点是可以立即支持所有docutils输出格式(但是您可能并不在意,因为大多数降价工具已经存在)。无需从头开发解析器的方法:

  • 您可以作弊并编写一个“解析器”,该解析器使用Pandoc将markdown转换为RST并将其传递给RST解析器:-)。

  • 您可以使用现有的markdown-> XML解析器,并将结果(使用XSLT?)转换为docutils模式。

  • 您可以使用一些现有的python markdown解析器,使您可以定义自定义渲染器,并使其构建docutils节点树。

  • 您可以分叉现有的RST阅读器,删除与降价无关的所有内容并更改不同的语法(此比较可能会有所帮助)…
    编辑:除非您准备好对其进行大量测试,否则我不建议您使用此路由。Markdown已经有太多不同的方言,这很可能会导致另一方言……

更新: https : //github.com/sgenoud/remarkdown是docutils的降价阅读器。它没有采用上述任何快捷方式,而是使用了受peg-markdown启发的Parsley PEG语法。尚不支持指令。

更新:https : //github.com/rtfd/recommonmark,这是另一个docutils阅读器,ReadTheDocs本身支持。 源自remarkdown,但使用CommonMark-py解析器。不支持指令,但可以将或多或少的自然Markdown语法转换为适当的结构,例如toctree的链接列表。对于其他需求,带```eval_rst围栏的块可让您嵌入任何rST指令。


所有情况下,您都需要发明Markdown的扩展来表示Sphinx指令和角色。虽然您可能不需要全部,但有些.. toctree::是必不可少的。
我认为这是最困难的部分。Sphinx扩展之前的reStructuredText已经比markdown丰富。即使是大幅扩展的降价促销(例如pandoc),也大多是rST功能集的子集。有很多方面需要解决!

在实现方面,最简单的方法是添加泛型构造以表达任何docutils角色/指令。语法启发的显而易见的候选人是:

  • pandoc和其他一些实现已允许在许多内联和块构造中使用属性语法。例如`foo`{.method}-> `foo`:method:
  • HTML / XML。从<span class="method">foo</span>只是插入docutils内部XML的kludgiest方法开始!
  • 某种针对指令的YAML?

但是这样的通用映射不会是最降价十岁上下的解决方案。目前最活跃的地方,讨论降价扩展是https://groups.google.com/forum/#!topic/pandoc-discusshttps://开头github.com/scholmd/scholmd/

这也意味着您不能只使用markdown解析器而不以某种方式扩展它。潘多克(Pandoc)通过支持定制过滤器(fils),再次履行其作为瑞士转换文件的军刀的声誉。(实际上,如果我要采用这种方法,我会尝试在docutils读取器/变压器/编写器与pandoc读取器/过滤器/编写器之间建立通用的桥梁。这超出了您的需求,但收益将远远超过狮身人面像/降价。)


另一个疯狂的主意:扩展reStructuredText而不是扩展markdown来处理Sphinx,以(主要)支持markdown的超集!这样做的好处是,您可以按原样使用任何Sphinx功能,但可以在markdown中编写大多数内容。

已经有相当多的语法重叠 ; 最明显的是链接语法不兼容。我认为,如果您为markdown链接和###-style标头添加了对RST的支持,并将默认`backticks`角色更改为文字,并且可能将缩进的块更改为文字(现在的RST支持> ...引号),那么您将获得支持大多数markdown的有用信息。

The “proper” way to do that would be to write a docutils parser for markdown. (Plus a Sphinx option to choose the parser.) The beauty of this would be instant support for all docutils output formats (but you might not care about that, as similar markdown tools already exist for most). Ways to approach that without developing a parser from scratch:

  1. You could cheat and write a “parser” that uses Pandoc to convert markdown to RST and pass that to the RST parser :-).

  2. You can use an existing markdown->XML parser and transform the result (using XSLT?) to the docutils schema.

  3. You could take some existing python markdown parser that lets you define a custom renderer and make it build docutils node tree.

  4. You could fork the existing RST reader, ripping out everything irrelevant to markdown and changing the different syntaxes (this comparison might help)…
    EDIT: I don’t recommend this route unless you’re prepared to heavily test it. Markdown already has too many subtly different dialects and this will likely result in yet-another-one…

UPDATE: https://github.com/sgenoud/remarkdown is a markdown reader for docutils. It didn’t take any of the above shortcuts but uses a Parsley PEG grammar inspired by peg-markdown.

UPDATE: https://github.com/readthedocs/recommonmark and is another docutils reader, natively supported on ReadTheDocs. Derived from remarkdown but uses the CommonMark-py parser.

  • It can convert specific more-or-less natural Markdown syntaxes to appropriate structures e.g. list of links to a toctree. * Doesn’t have generic native syntax for roles.
  • Supports embedding any rST content, including directives, with an ```eval_rst fenced block as well as a shorthand for directives DIRECTIVE_NAME:: ....

UPDATE: MyST is yet another docutins/Sphinx reader. Based on markdown-it-py, CommonMark compatible.

  • Has a generic {ROLE_NAME}`...` syntax for roles.
  • Has a generic syntax for directives with ```{DIRECTIVE_NAME} ... fenced blocks.

In all cases, you’ll need to invent extensions of Markdown to represent Sphinx directives and roles. While you may not need all of them, some like .. toctree:: are essential.
This I think is the hardest part. reStructuredText before the Sphinx extensions was already richer than markdown. Even heavily extended markdown, such as pandoc’s, is mostly a subset of rST feature set. That’s a lot of ground to cover!

Implementation-wise, the easiest thing is adding a generic construct to express any docutils role/directive. The obvious candidates for syntax inspiration are:

  • Attribute syntax, which pandoc and some other implementations already allow on many inline and block constructs. For example `foo`{.method} -> `foo`:method:.
  • HTML/XML. From <span class="method">foo</span> to the kludgiest approach of just inserting docutils internal XML!
  • Some kind of YAML for directives?

But such a generic mapping will not be the most markdown-ish solution… Currently most active places to discuss markdown extensions are https://groups.google.com/forum/#!topic/pandoc-discuss, https://github.com/scholmd/scholmd/

This also means you can’t just reuse a markdown parser without extending it somehow. Pandoc again lives up to its reputation as the swiss army knife of document conversion by supporting custom filtes. (In fact, if I were to approach this I’d try to build a generic bridge between docutils readers/transformers/writers and pandoc readers/filters/writers. It’s more than you need but the payoff would be much wider than just sphinx/markdown.)


Alternative crazy idea: instead of extending markdown to handle Sphinx, extend reStructuredText to support (mostly) a superset of markdown! The beauty is you’ll be able to use any Sphinx features as-is, yet be able to write most content in markdown.

There is already considerable syntax overlap; most notably link syntax is incompatible. I think if you add support to RST for markdown links, and ###-style headers, and change default `backticks` role to literal, and maybe change indented blocks to mean literal (RST supports > ... for quotations nowdays), you’ll get something usable that supports most markdown.


回答 1

您可以在同一Sphinx项目中使用Markdown和reStructuredText。如何完成此操作,请参见“ 阅读文档”

安装recommonmark(pip install recommonmark),然后编辑conf.py

from recommonmark.parser import CommonMarkParser

source_parsers = {
    '.md': CommonMarkParser,
}

source_suffix = ['.rst', '.md']

我已经在Github上创建了一个小示例项目(serra / sphinx-with-markdown),展示了它的工作原理。它使用CommonMark 0.5.4和recommonmark 0.4.0。

You can use Markdown and reStructuredText in the same Sphinx project. How to do this is succinctly documented on Read The Docs.

Install recommonmark (pip install recommonmark) and then edit conf.py:

from recommonmark.parser import CommonMarkParser

source_parsers = {
    '.md': CommonMarkParser,
}

source_suffix = ['.rst', '.md']

I’ve created a small example project on Github (serra/sphinx-with-markdown) demonstrating how (and that) it works. It uses CommonMark 0.5.4 and recommonmark 0.4.0.


回答 2

它不使用Sphinx,但是MkDocs将使用Markdown构建您的文档。我也讨厌rst,到目前为止,我非常喜欢MkDocs。

This doesn’t use Sphinx, but MkDocs will build your documentation using Markdown. I also hate rst, and have really enjoyed MkDocs so far.


回答 3

更新:现在已正式支持此功能,并在sphinx docs中进行了记录

看起来,基本的实现方式已将其引入Sphinx,但尚未达成共识。查看github问题评论

安装依赖项:

pip install commonmark recommonmark

调整conf.py

source_parsers = {
    '.md': 'recommonmark.parser.CommonMarkParser',
}
source_suffix = ['.rst', '.md']

Update: this is now officially supported and documented in the sphinx docs.

It looks like a basic implementation has made it’s way into Sphinx but word has not gotten round yet. See github issue comment

install dependencies:

pip install commonmark recommonmark

adjust conf.py:

source_parsers = {
    '.md': 'recommonmark.parser.CommonMarkParser',
}
source_suffix = ['.rst', '.md']

回答 4

Markdown和ReST做不同的事情。

RST提供了用于处理文档的对象模型。

Markdown提供了一种雕刻文字的方法。

想要从sphinx项目中引用您的Markdown内容似乎是合理的,使用RST存根整个信息结构和较大文档的流程。让markdown做什么,这使作者可以专注于编写文本。

有没有一种方法可以引用降价域名,仅按原样雕刻内容?RST / sphinx似乎已经照顾好功能,例如toctree没有在markdown中复制它们。

Markdown and ReST do different things.

RST provides an object model for working with documents.

Markdown provides a way to engrave bits of text.

It seems reasonable to want to reference your bits of Markdown content from your sphinx project, using RST to stub out the overall information architecture and flow of a larger document. Let markdown do what it does, which is allow writers to focus on writing text.

Is there a way to reference a markdown domain, just to engrave the content as-is? RST/sphinx seems to have taken care of features like toctree without duplicating them in markdown.


回答 5


回答 6

我同意贝尼(Beni)的建议,将pandoc用于此任务。安装后,以下脚本会将源目录中的所有markdown文件转换为rst文件,以便您可以将所有文档写入markdown中。希望这对其他人有用。

#!/usr/bin/env python
import os
import subprocess

DOCUMENTATION_SOURCE_DIR = 'documentation/source/'
SOURCE_EXTENSION = '.md'
OUTPUT_EXTENSION = '.rst'

for _, __, filenames in os.walk(DOCUMENTATION_SOURCE_DIR):
    for filename in filenames:
        if filename.endswith('.md'):
            filename_stem = filename.split('.')[0]
            source_file = DOCUMENTATION_SOURCE_DIR + filename_stem + SOURCE_EXTENSION
            output_file = DOCUMENTATION_SOURCE_DIR + filename_stem + OUTPUT_EXTENSION
            command = 'pandoc -s {0} -o {1}'.format(source_file, output_file)
            print(command)
            subprocess.call(command.split(' '))

I went with Beni’s suggestion of using pandoc for this task. Once installed the following script will convert all markdown files in the source directory to rst files, so that you can just write all your documentation in markdown. Hope this is useful for others.

#!/usr/bin/env python
import os
import subprocess

DOCUMENTATION_SOURCE_DIR = 'documentation/source/'
SOURCE_EXTENSION = '.md'
OUTPUT_EXTENSION = '.rst'

for _, __, filenames in os.walk(DOCUMENTATION_SOURCE_DIR):
    for filename in filenames:
        if filename.endswith('.md'):
            filename_stem = filename.split('.')[0]
            source_file = DOCUMENTATION_SOURCE_DIR + filename_stem + SOURCE_EXTENSION
            output_file = DOCUMENTATION_SOURCE_DIR + filename_stem + OUTPUT_EXTENSION
            command = 'pandoc -s {0} -o {1}'.format(source_file, output_file)
            print(command)
            subprocess.call(command.split(' '))

回答 7

有一种解决方法。
sphinx-quickstart.py脚本生成一个Makefile。
每次您想要生成文档时,都可以轻松地从Makefile中调用Pandoc,以将Markdown转换为reStructuredText。

There is a workaround.
The sphinx-quickstart.py script generates a Makefile.
You can easily invoke Pandoc from the Makefile every time you’d like to generate the documentation in order to convert Markdown to reStructuredText.


回答 8

这是一个新选项。MyST向Markdown添加了一些功能,这些功能使Sphinx可以像rst一样构建文档。 https://myst-parser.readthedocs.io/en/latest/

Here’s a new option. MyST adds some features to Markdown that allow Sphinx to build docs like rst does. https://myst-parser.readthedocs.io/en/latest/


回答 9

请注意,以下maven插件完全支持使用maven和嵌入式Sphinx + MarkDown支持构建文档:

https://trustin.github.io/sphinx-maven-plugin/index.html

<plugin>
  <groupId>kr.motd.maven</groupId>
  <artifactId>sphinx-maven-plugin</artifactId>
  <version>1.6.1</version>
  <configuration>
    <outputDirectory>${project.build.directory}/docs</outputDirectory>
  </configuration>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Note that building documentation using maven and embedded Sphinx + MarkDown support is fully supported by following maven plugin :

https://trustin.github.io/sphinx-maven-plugin/index.html

<plugin>
  <groupId>kr.motd.maven</groupId>
  <artifactId>sphinx-maven-plugin</artifactId>
  <version>1.6.1</version>
  <configuration>
    <outputDirectory>${project.build.directory}/docs</outputDirectory>
  </configuration>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Rich-Rich是一个Python库,用于终端中的富文本和美观的格式设置

中文 readme·Lengua española readme·Deutsche readme·Läs på svenska·日本語 readme·한국어 readme

Rich是一个Python库,用于富有终端中的文本和美观的格式

这个Rich API使您可以轻松地向终端输出添加颜色和样式。Rich还可以呈现漂亮的表格、进度条、标记、语法突出显示的源代码、回溯等等–开箱即用

有关Rich的视频介绍,请参阅calmcode.io通过@fishnets88

看看什么people are saying about Rich

兼容性

Rich适用于Linux、OSX和Windows。真彩色/表情符号适用于新的Windows终端,经典终端仅限16色。Rich需要Python 3.6.1或更高版本

Rich与Jupyter notebooks无需额外配置

正在安装

随一起安装pip或您最喜欢的PyPI包管理器

pip install rich

运行以下命令在您的终端上测试Rich Output:

python -m rich

丰富多彩的印刷品

若要毫不费力地向应用程序添加丰富的输出,可以将rich print方法,该方法与内置Python函数具有相同的签名。试试这个:

from rich import print

print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())

丰富的REPL

Rich可以安装在Python REPL中,这样任何数据结构都会非常漂亮地打印和突出显示

>>> from rich import pretty
>>> pretty.install()

使用控制台

要更好地控制富终端内容,请导入并构造Console对象

from rich.console import Console

console = Console()

Console对象有一个print方法,该方法的接口有意与构建的print功能。下面是一个使用示例:

console.print("Hello", "World!")

如您所料,这将打印出来"Hello World!"去航站楼。请注意,与建筑不同的是print函数时,Rich将对文本进行自动换行以适应终端宽度

有几种方法可以将颜色和样式添加到输出中。您可以为整个输出设置样式,方法是将style关键字参数。下面是一个示例:

console.print("Hello", "World!", style="bold red")

输出将如下所示:

对于一次设置一行文本的样式来说,这是很好的。对于更细粒度的样式,Rich呈现了一个特殊的标记,该标记在语法上类似于bbcode下面是一个示例:

console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].")

您可以使用Console对象以最小的工作量生成复杂的输出。请参阅Console API详细信息请参阅文档

丰富考察

里奇有一个inspect可以生成有关任何Python对象(如类、实例或构建)的报告的函数

>>> my_list = ["foo", "bar"]
>>> from rich import inspect
>>> inspect(my_list, methods=True)

请参阅inspect docs有关详细信息,请参阅

丰富的图书馆

RICH包含多个建筑可渲染对象您可以使用在CLI中创建优雅的输出,并帮助您调试代码

有关详细信息,请单击以下标题:

日志

Console对象有一个log()方法,该方法具有类似于print(),而且还呈现当前时间的列以及进行调用的文件和行。默认情况下,Rich将对Python结构和REPR字符串进行语法高亮显示。如果您记录一个集合(例如,词典或列表),Rich会漂亮地打印它,以便它可以放在可用的空间中。以下是其中一些功能的示例

from rich.console import Console
console = Console()

test_data = [
    {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",},
    {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
    {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"},
]

def test_log():
    enabled = False
    context = {
        "foo": "bar",
    }
    movies = ["Deadpool", "Rise of the Skywalker"]
    console.log("Hello from", console, "!")
    console.log(test_data, log_locals=True)


test_log()

以上将产生以下输出:

请注意log_locals参数,该参数输出一个包含调用log方法的局部变量的表

LOG方法可用于登录到终端,用于长时间运行的应用程序(如服务器),但也是非常好的调试辅助工具

日志记录处理程序

您还可以使用内置的Handler class对来自Python日志记录模块的输出进行格式化和着色。以下是输出的示例:

表情符号

要在控制台输出中插入表情符号,请将名称放在两个冒号之间。下面是一个示例:

>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:")
😃 🧛 💩 👍 🦝

请明智地使用此功能

表格

丰富的可以灵活地呈现tables使用Unicode方框字符。边框、样式、单元格对齐等有多种格式选项

上面的动画是用table_movie.py在Examples目录中

下面是一个更简单的表格示例:

from rich.console import Console
from rich.table import Table

console = Console()

table = Table(show_header=True, header_style="bold magenta")
table.add_column("Date", style="dim", width=12)
table.add_column("Title")
table.add_column("Production Budget", justify="right")
table.add_column("Box Office", justify="right")
table.add_row(
    "Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
)
table.add_row(
    "May 25, 2018",
    "[red]Solo[/red]: A Star Wars Story",
    "$275,000,000",
    "$393,151,347",
)
table.add_row(
    "Dec 15, 2017",
    "Star Wars Ep. VIII: The Last Jedi",
    "$262,000,000",
    "[bold]$1,332,539,889[/bold]",
)

console.print(table)

这将产生以下输出:

请注意,控制台标记的呈现方式与print()log()事实上,Rich可以呈现的任何内容都可能包含在标题/行中(甚至其他表)

这个Table类足够智能,可以调整列的大小以适应终端的可用宽度,并根据需要对文本进行换行。下面是相同的示例,端子比上表小:

进度条

丰富的可以呈现多个无闪烁progress用于跟踪长期运行任务的条形图

对于基本用法,将任何序列包装在track函数并迭代结果。下面是一个示例:

from rich.progress import track

for step in track(range(100)):
    do_step(step)

添加多个进度条并不难。以下是文档中的一个示例:

这些列可以配置为显示您想要的任何详细信息。内置列包括完成百分比、文件大小、文件速度和剩余时间。下面是另一个示例,显示正在进行的下载:

要亲自尝试此功能,请参见examples/downloader.py它可以在显示进度的同时同时下载多个URL

状态

对于很难计算进度的情况,可以使用status方法,该方法将显示“微调器”动画和消息。动画不会阻止您正常使用控制台。下面是一个示例:

from time import sleep
from rich.console import Console

console = Console()
tasks = [f"task {n}" for n in range(1, 11)]

with console.status("[bold green]Working on tasks...") as status:
    while tasks:
        task = tasks.pop(0)
        sleep(1)
        console.log(f"{task} complete")

这将在终端中生成以下输出

微调器动画借用自cli-spinners您可以通过指定spinner参数。运行以下命令以查看可用值:

python -m rich.spinner

上面的命令在终端中生成以下输出:

Rich可以呈现一个tree带着指引线。树是显示文件结构或任何其他分层数据的理想选择

树的标签可以是简单的文本,也可以是Rich可以呈现的任何其他内容。运行以下命令进行演示:

python -m rich.tree

这将生成以下输出:

请参阅tree.py显示任何目录的树视图的脚本示例,类似于Linuxtree命令

Rich可以整齐地呈现内容columns具有相等或最佳宽度的。下面是(MacOS/Linux)的一个非常基本的克隆ls按列显示目录列表的命令:

import os
import sys

from rich import print
from rich.columns import Columns

directory = os.listdir(sys.argv[1])
print(Columns(directory))

下面的屏幕截图是columns example它以列的形式显示从API拉取的数据:

降价

Rich可以渲染markdown并且合理地将格式转换到终端

若要呈现标记,请将Markdown类,并使用包含标记代码的字符串构造它。然后将其打印到控制台。下面是一个示例:

from rich.console import Console
from rich.markdown import Markdown

console = Console()
with open("README.md") as readme:
    markdown = Markdown(readme.read())
console.print(markdown)

这将产生类似以下内容的输出:

语法突出显示

Rich使用pygments要实施的库syntax highlighting用法类似于呈现标记;构造Syntax对象,并将其打印到控制台。下面是一个示例:

from rich.console import Console
from rich.syntax import Syntax

my_code = '''
def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
    """Iterate and generate a tuple with a flag for first and last value."""
    iter_values = iter(values)
    try:
        previous_value = next(iter_values)
    except StopIteration:
        return
    first = True
    for value in iter_values:
        yield first, False, previous_value
        first = False
        previous_value = value
    yield first, True, previous_value
'''
syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True)
console = Console()
console.print(syntax)

这将产生以下输出:

跟踪回溯

Rich可以渲染beautiful tracebacks它们比标准Python回溯更容易阅读和显示更多代码。您可以将Rich设置为默认的回溯处理程序,这样所有未捕获的异常都将由Rich呈现

下面是它在OSX上的样子(与Linux类似):

所有丰富渲染器都使用Console Protocol,您还可以使用它来实现您自己的富内容

为企业发财致富

作为Tidelift订阅的一部分提供

Rich和数千个其他软件包的维护者正在与Tidelift合作,为您用来构建应用程序的开源软件包提供商业支持和维护。节省时间、降低风险并提高代码的健全性,同时付钱给您所使用的包的维护者。Learn more.

使用Rich的项目

以下是一些使用Rich的项目: