如何使用docutils将reStructuredText转为HTML?代码输出异常求助
Ah, I see the issue here! Your code is using the default writer for publish_string, which outputs a pseudo-XML representation of the document tree instead of proper HTML. That’s why you’re seeing those escaped tags and raw structure instead of the formatted HTML you expect—unlike the rst2html.py command-line tool, which automatically uses the HTML writer under the hood.
To fix this, you just need to explicitly specify the HTML writer when calling publish_string, and optionally set the output encoding to get a readable string instead of bytes. Here’s your corrected code:
from docutils.core import publish_string input_string = ("Heading\n" "=======\n" "\n" "1. With 24 widgets pull a **long** one;\n" "2. with fewer, push a **wide** one.\n") # Use the HTML writer and request unicode output for a clean string html = publish_string(input_string, writer_name='html', output_encoding='unicode') print(html)
What’s changed?
writer_name='html': This tells docutils to use the same HTML writer thatrst2html.pyuses, generating proper HTML markup instead of the pseudo-XML tree.output_encoding='unicode': By default,publish_stringreturns a bytes object. Setting this parameter gives you a Python string directly, making it easier to print or manipulate without extra decoding steps.
When you run this corrected code, you’ll get a full HTML document with your heading, numbered list, and bold text properly formatted—just like the output from rst2html.py.
内容的提问来源于stack exchange,提问作者Psionman

