Cogapp - Content Generator

3.6.0 · active · verified Fri Apr 17

Cogapp, currently at version 3.6.0, is a content generator that executes Python snippets embedded within source files (like Python, C, HTML, or plain text) to produce updated output. It helps keep documentation, code examples, and derived content in sync with their source, primarily operating as a command-line tool. Releases are generally stable, with new versions addressing bug fixes and minor enhancements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use cogapp to generate content within a file. It creates a sample file with a `[[[cog ... ]]]` block, runs cogapp in-place using `python -m cogapp`, and then prints the updated file content. The subprocess call ensures cogapp is run robustly even if the `cog` executable is not directly in PATH.

import subprocess
import os
import datetime

# Create a dummy input file
file_content = """
Hello, cogapp user!
This line will be replaced by cog.
[[[cog
print(f"The current UTC time is: {datetime.datetime.utcnow().isoformat(timespec='seconds')}")
]]]
This line will remain.
"""
input_filename = "cog_example.txt"
with open(input_filename, "w") as f:
    f.write(file_content)

print(f"Created {input_filename} with initial content:")
with open(input_filename, "r") as f:
    print(f.read())

# Run cog in-place
print(f"\nRunning 'python -m cogapp -r {input_filename}'...")
try:
    result = subprocess.run([
        "python", "-m", "cogapp", "-r", input_filename
    ], capture_output=True, text=True, check=True)
    
    if result.stdout:
        print("Cog output (stdout):")
        print(result.stdout)
    if result.stderr:
        print("Cog errors (stderr):")
        print(result.stderr)
    
    print(f"\nUpdated {input_filename} content:")
    with open(input_filename, "r") as f:
        print(f.read())

except subprocess.CalledProcessError as e:
    print(f"Error running cogapp: {e}")
    print(f"Stdout: {e.stdout}")
    print(f"Stderr: {e.stderr}")
finally:
    # Clean up
    if os.path.exists(input_filename):
        os.remove(input_filename)
    print(f"\nCleaned up {input_filename}.")

view raw JSON →