### Install Cog using pip Source: https://github.com/nedbat/cog/blob/main/docs/index.md This command installs the Cog application using Python's package installer. Ensure you have Python 3.10 or higher installed. ```bash python3 -m pip install cogapp ``` -------------------------------- ### Cog Marker Examples Source: https://github.com/nedbat/cog/blob/main/docs/source.md Demonstrates different ways to mark the beginning of executable Python code in source files. The format of the marker lines is flexible as long as the special character sequence is present. ```text //[[[cog ``` ```text /* cog starts now: [[[cog */ ``` ```text -- [[[cog (this is cog Python code) ``` ```text #if 0 // [[[cog ``` -------------------------------- ### Cog Compact Form Example Source: https://github.com/nedbat/cog/blob/main/docs/source.md Shows the compact form for single Python lines where begin and end markers are on the same line. This is useful for simple imports or single-line code execution. ```cpp // blah blah //[[[cog import MyModule as m; m.generateCode() ]]] //[[[end]]] ``` -------------------------------- ### Cog SQL File Example with Prefixes Source: https://github.com/nedbat/cog/blob/main/docs/source.md Illustrates how Cog handles prefixed Python code in files like SQL where markers and code share a common prefix. The prefixes are removed before execution and not included in the output. ```sql --[[[cog -- import cog -- for table in ['customers', 'orders', 'suppliers']: -- cog.outl("drop table %s;" % table) --]]] ``` ```sql --[[[end]]] ``` -------------------------------- ### Process files with specified markers Source: https://github.com/nedbat/cog/blob/main/docs/running.md Use the `-s` flag to specify marker syntax for different file types. This example processes C++ files with C++ markers, an SQL file with SQL markers, and a text file with no markers. ```bash $ cog -s " //**cogged**" @cogfiles.txt ``` -------------------------------- ### Generate text with line suffixes Source: https://github.com/nedbat/cog/blob/main/docs/running.md This example demonstrates how Cog generates text with a specified suffix appended to each line. The Python code uses `cog.outl` to print lines with the suffix. ```text [[[cog cog.outl('Three times:\n') for i in range(3): cog.outl('This is line %d' % i) ]]] Three times: //(generated) This is line 0 //(generated) This is line 1 //(generated) This is line 2 //(generated) [[[end]]] ``` -------------------------------- ### Generate C++ Declarations with Cog Source: https://github.com/nedbat/cog/blob/main/docs/index.md This example demonstrates how to use Cog to generate C++ function declarations within a C++ source file. The Python code is embedded within C++ comments to be ignored by the C++ compiler. ```cpp // This is my C++ file. ... /*[[[cog import cog fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing'] for fn in fnames: cog.outl("void %s();" % fn) ]]]*///[[[end]]] ... ``` ```cpp // This is my C++ file. ... /*[[[cog import cog fnames = ['DoSomething', 'DoAnotherThing', 'DoLastThing'] for fn in fnames: cog.outl("void %s();" % fn) ]]]*/ void DoSomething(); void DoAnotherThing(); void DoLastThing(); //[[[end]]] ... ``` -------------------------------- ### Generate output with checksum and Python code Source: https://github.com/nedbat/cog/blob/main/docs/running.md Cog can generate output accompanied by a checksum for integrity checking. This example uses Python code within Cog markers to generate a sequence of numbers. ```sql --[[[cog -- import cog -- for i in range(10): -- cog.out("%d " % i) --]]] 0 1 2 3 4 5 6 7 8 9 --[[[end]]] (sum: vXcVMEUp9m) ``` -------------------------------- ### Process template file multiple times with different definitions Source: https://github.com/nedbat/cog/blob/main/docs/running.md Cog can process a template file multiple times, each time with different definitions for variables. This example generates two output files from a single template, each with a different value for `thefile`. ```text template.h -D thefile=data1.xml -o data1.h template.h -D thefile=data2.xml -o data2.h ``` -------------------------------- ### Display Cog help information Source: https://github.com/nedbat/cog/blob/main/docs/running.md View the command-line interface options and usage instructions. ```text $ cog -h cog - generate content with inlined Python code. cog [OPTIONS] [INFILE | @FILELIST | &FILELIST] ... positional arguments: [INFILE | @FILELIST | &FILELIST] FILELIST is the name of a text file containing file names or other @FILELISTs. For @FILELIST, paths in the file list are relative to the working directory where cog was called. For &FILELIST, paths in the file list are relative to the file list location." options: -h, --help show this help message and exit -c Checksum the output to protect it against accidental change. -d Delete the Python code from the output file. -D name=val Define a global string available to your Python code. -e Warn if a file has no cog code in it. -I PATH Add PATH to the list of directories for data files and modules. -n ENCODING Use ENCODING when reading and writing files. -o OUTNAME Write the output to OUTNAME. -p PROLOGUE Prepend the Python source with PROLOGUE. Useful to insert an import line. Example: -p "import math" -P Use print() instead of cog.outl() for code output. -r Replace the input file with the output. -s STRING Suffix all generated output lines with STRING. -U Write the output with Unix newlines (only LF line- endings). -w CMD Use CMD if the output file needs to be made writable. A %s in the CMD will be filled with the filename. -x Excise all the generated output without running the Pythons. -z The end-output marker can be omitted, and is assumed at eof. -v Print the version of cog and exit. --check Check that the files would not change if run again. --check-fail-msg MSG If --check fails, include MSG in the output to help devs understand how to run cog in your project. --diff With --check, show a diff of what failed the check. --markers 'START END END-OUTPUT' The patterns surrounding cog inline instructions. Should include three values separated by spaces, the start, end, and end-output markers. Defaults to '[[[cog ]]] [[[end]]]'. --verbosity VERBOSITY Control the amount of output. 2 (the default) lists all files, 1 lists only changed files, 0 lists no files. ``` -------------------------------- ### Process files using a list file Source: https://github.com/nedbat/cog/blob/main/docs/running.md Use an @-prefixed file to provide a list of files for Cog to process. ```bash $ cog @files_to_cog.txt ``` -------------------------------- ### Write multi-line strings with cog.out Source: https://github.com/nedbat/cog/blob/main/docs/module.md Use dedent and trimblanklines to format multi-line strings cleanly when writing to the output file. ```default cog.out(""" These are lines I want to write into my source file. """, dedent=True, trimblanklines=True) ``` -------------------------------- ### Define global variables from command line Source: https://github.com/nedbat/cog/blob/main/docs/running.md Use the `-D` flag to define global variables that can be referenced within your Cog templates. Values are always interpreted as Python strings. ```bash $ cog -D version=3.4.1 @cogfiles2.txt ``` ```bash $ cog -D thefile=fooey.xml mycode.txt ``` ```bash $ cog -D NUM_TO_DO=12 ``` -------------------------------- ### Overwrite input files with output Source: https://github.com/nedbat/cog/blob/main/docs/running.md The `-r` flag enables overwriting. Use `-w` to provide a command for making unwritable files writable, such as checking them out from source control. ```bash $ cog -r -w "p4 edit %s" @files_to_cog.txt ``` -------------------------------- ### cog.out Function Source: https://github.com/nedbat/cog/blob/main/docs/module.md Writes text to the output file. Supports options for dedenting and trimming blank lines from multi-line strings. ```APIDOC ## cog.out ### Description Writes text to the output file. The `sOut` parameter is the string to write. The `dedent` option removes common initial whitespace from lines, and `trimblanklines` removes initial and trailing blank lines. These options are useful for multi-line strings. ### Parameters - **sOut** (string) - Required - The text to write to the output. - **dedent** (boolean) - Optional - If True, removes common leading whitespace from lines. - **trimblanklines** (boolean) - Optional - If True, removes initial and trailing blank lines. ### Request Example ```python cog.out(""" These are lines I want to write into my source file. """, dedent=True, trimblanklines=True) ``` ``` -------------------------------- ### XML Schema Definition Source: https://github.com/nedbat/cog/blob/main/success/cog-success.rst Defines properties with names and types using XML. This file serves as the data source for code generation. ```xml ``` -------------------------------- ### C++ File with Cog Generator Source: https://github.com/nedbat/cog/blob/main/success/cog-success.rst A C++ header file demonstrating inlined Python code using Cog markers. The Python script iterates over an XML file to generate enum values. ```cpp // SchemaPropEnum.h enum SchemaPropEnum { /* [[[cog import cog, handyxml for p in handyxml.xpath('Properties.xml', '//property'): cog.outl("Property%s," % p.name) ]]] */ // [[[end]]] }; ``` -------------------------------- ### Read files with older hex checksum format Source: https://github.com/nedbat/cog/blob/main/docs/running.md Cog supports reading files with an older hex checksum format. When regenerated, these files will be updated to the shorter base64 format automatically. ```sql --[[[end]]] (checksum: bd7715304529f66c4d3493e786bb0f1f) ``` -------------------------------- ### Check for changes without modifying files Source: https://github.com/nedbat/cog/blob/main/docs/running.md Use the `--check` option to verify that files would not change if Cog were run. This is useful in CI environments. The `--diff` option shows the changes that would occur. ```bash $ cog --check ``` ```bash $ cog --diff ``` -------------------------------- ### Append output line suffixes Source: https://github.com/nedbat/cog/blob/main/docs/running.md The `-s` switch appends a specified suffix to every non-blank generated line, making it easier to identify generated content when grepping source files. ```bash $ cog -s " //(generated)" mycode.txt ``` -------------------------------- ### Provide custom failure message for --check Source: https://github.com/nedbat/cog/blob/main/docs/running.md The `--check-fail-msg` option allows you to specify a custom message when the `--check` option fails. This can be used to provide instructions on how to fix the problem. ```bash $ cog --check-fail-msg "Run 'cog -r' to update the file." ``` -------------------------------- ### Cog Module Attributes Source: https://github.com/nedbat/cog/blob/main/docs/module.md Provides access to file paths and line number information within the current code chunk. ```APIDOC ## Cog Module Attributes ### Description These attributes provide contextual information about the input and output files, as well as the current code chunk's position. ### Attributes - **cog.inFile** (string) - The absolute path of the input file being processed. - **cog.outFile** (string) - The absolute path of the output file being generated. - **cog.firstLineNum** (integer) - The line number in the input file where the current Python code chunk begins. - **cog.previous** (string) - The text output generated by the previous execution of this Python code chunk. Useful for comparing or reusing previous output. ``` -------------------------------- ### Invoke Cog as a Python module Source: https://github.com/nedbat/cog/blob/main/docs/running.md Run Cog using the Python interpreter instead of the direct command-line utility. ```bash $ python3 -m cogapp [options] [arguments] ``` -------------------------------- ### cog.msg Function Source: https://github.com/nedbat/cog/blob/main/docs/module.md Prints a message to standard output, prefixed with 'Message: '. ```APIDOC ## cog.msg ### Description Prints the provided message string (`msg`) to standard output, prefixed with "Message: ". ### Parameters - **msg** (string) - Required - The message to print. ### Request Example ```python cog.msg("This is an informational message.") ``` ``` -------------------------------- ### cog.outl Function Source: https://github.com/nedbat/cog/blob/main/docs/module.md Identical to cog.out, but automatically appends a newline character after writing the text. ```APIDOC ## cog.outl ### Description Same as `cog.out`, but adds a trailing newline character after writing the provided text. ### Parameters - **sOut** (string) - Required - The text to write to the output. - **dedent** (boolean) - Optional - If True, removes common leading whitespace from lines. - **trimblanklines** (boolean) - Optional - If True, removes initial and trailing blank lines. ### Request Example ```python cog.outl("A line of text with a newline.") ``` ``` -------------------------------- ### cog.error Function Source: https://github.com/nedbat/cog/blob/main/docs/module.md Raises an exception with the provided message, without including a traceback. ```APIDOC ## cog.error ### Description Raises an exception with the provided message (`msg`). This function is designed to avoid including a traceback in the output. ### Parameters - **msg** (string) - Required - The error message text. ### Request Example ```python try: cog.error("Something went wrong.") except Exception as e: print(e) # Output: Something went wrong. ``` ``` -------------------------------- ### Generated C++ Enum Values Source: https://github.com/nedbat/cog/blob/main/success/cog-success.rst The output of the Cog generator after processing the C++ file. It shows the enum values generated from the XML schema. ```cpp // SchemaPropEnum.h enum SchemaPropEnum { /* [[[cog import cog, handyxml for p in handyxml.xpath('Properties.xml', '//property'): cog.outl("Property%s," % p.name) ]]] */ PropertyId, PropertyRevNum, PropertySubject, PropertyModDate, // [[[end]]] }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.