如何将Python脚本运行结果传入AsciiDoc(adoc)文件?
Got it, let's break down how to feed your Python script's output into an AsciiDoc file—here are several practical approaches I’ve relied on for projects:
1. Directly Generate/Append AsciiDoc Content in Python
The most straightforward way is to have your Python script format its output into valid AsciiDoc syntax, then write or append it directly to an .adoc file. This works great if you want full control over how the output is styled in the document.
Example code:
# First, get your script's core output (e.g., a dataset) def fetch_script_results(): return [ ["Task Name", "Status", "Completion Time"], ["Data Processing", "Success", "12s"], ["Report Generation", "Warning", "24s"] ] # Convert the data to an AsciiDoc table def convert_to_adoc_table(data): header = "| " + " | ".join(data[0]) + "\n" separator = "|" + "|".join(["---"] * len(data[0])) + "\n" rows = "\n".join(["| " + " | ".join(map(str, row)) for row in data[1:]]) return f"[cols=\"{len(data[0])}*\"]\n|===\n{header}{separator}{rows}\n|===" # Write to your AsciiDoc file if __name__ == "__main__": adoc_formatted_content = convert_to_adoc_table(fetch_script_results()) # Use "w" to overwrite, "a" to append to an existing file with open("project_report.adoc", "a") as f: f.write("\n## Python Script Execution Results\n\n") f.write(adoc_formatted_content)
2. Use Asciidoctor's include Directive
If you prefer keeping your Python script and AsciiDoc file separate, have your script output raw results to a text file, then use Asciidoctor's include to pull that content into your .adoc file. This keeps your main document clean and makes it easy to update results without editing the adoc directly.
Step 1: Python script writes to a text file
with open("script_output.txt", "w") as f: f.write("### Key Metrics from Python Script\n") f.write("- Total records processed: 1500\n") f.write("- Error rate: 0.2%\n") f.write("- Average processing time per record: 0.04s\n")
Step 2: Reference the text file in your AsciiDoc
# Project Status Report This report includes real-time metrics from our data processing script: include::script_output.txt[]
For code-like output, add syntax highlighting:
## Debug Logs [source,python] ---- include::debug_output.txt[] ----
3. Command-Line Automation (For Pipelines)
If you’re working in a CI/CD pipeline or just want to automate the end-to-end flow, use command-line tools to pipe Python’s output into Asciidoctor or your adoc file.
Examples:
# Append Python's AsciiDoc-formatted output to your main adoc file python data_script.py >> main_document.adoc # Directly generate HTML/PDF from Python's output (no intermediate adoc file) python report_generator.py | asciidoctor -o final_report.html -
Note: Your Python script needs to print valid AsciiDoc syntax directly (e.g., print("# Script Results\n\n- Completed successfully")).
4. Asciidoctor Ruby Extension (For Advanced Use Cases)
If you need tight integration between Python and Asciidoctor (e.g., dynamic content on every compile), write a simple Ruby extension to call your Python script and inject its output.
Example extension (save as python_extension.rb):
Asciidoctor::Extensions.register do inline_macro do named :python_run process do |parent, script_path, attrs| # Run the Python script and capture output script_output = `python #{script_path}` # Insert the output as a paragraph in the document create_paragraph parent, script_output, attrs end end end
Then use it in your Asciidoctor file:
## Dynamic Results The latest data from our script: python_run::data_processor.py[]
Compile with the extension:
asciidoctor -r ./python_extension.rb document.adoc
Quick Tips
- Always escape special AsciiDoc characters (like
[,],|) in your Python output to avoid breaking document syntax. - For large outputs, stick with the
includemethod—it keeps your adoc file manageable and lets you refresh results without rewriting the document structure. - Use a Makefile to automate the full workflow (run Python script → compile adoc) with a single command.
内容的提问来源于stack exchange,提问作者Nika

