Code Generation
Tools for generating executable Python code from flowgraphs.
generate_code
Generate Python/C++ code from the current flowgraph.
Unlike the grcc command-line tool, this does not block on validation errors.
Validation warnings are included in the response for reference.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
output_dir | str | "" | Output directory (defaults to temp directory) |
Returns
Type: GeneratedCodeModel
Generated code result with path, validity, and warnings.
Example
result = generate_code(output_dir="/tmp")# Returns: GeneratedCodeModel(# file_path="/tmp/fm_receiver.py",# is_valid=True,# warnings=[]# )
# With validation warningsresult = generate_code()# Returns: GeneratedCodeModel(# file_path="/tmp/tmpXXXXXX/fm_receiver.py",# is_valid=False,# warnings=["audio_sink_0: Sample rate mismatch"]# )Notes
- Generated code includes XML-RPC server if the flowgraph has XML-RPC variables
- Output type (Python/C++) depends on
generate_optionsin flowgraph options - File name is derived from flowgraph title
evaluate_expression
Evaluate a Python expression in the flowgraph’s namespace.
Useful for testing parameter expressions before setting them.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
expr | str | - | Python expression to evaluate |
Returns
Type: Any
Result of the expression evaluation.
Example
# Arithmeticresult = evaluate_expression("101.1e6 + 200e3")# Using numpy (available in flowgraph namespace)result = evaluate_expression("np.pi * 2")# Returns: 6.283185307179586
# Complex expressionsresult = evaluate_expression("int(2e6 / 10)")# Returns: 200000create_embedded_python_block
Create an embedded Python block from source code.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
source_code | str | - | Python source code for the block |
block_name | str | None | None | Optional custom block name |
Returns
Type: str
The assigned block name.
Example
source = '''import numpy as npfrom gnuradio import gr
class my_multiplier(gr.sync_block): """Multiply input by a constant."""
def __init__(self, multiplier=2.0): gr.sync_block.__init__( self, name="my_multiplier", in_sig=[np.complex64], out_sig=[np.complex64] ) self.multiplier = multiplier
def work(self, input_items, output_items): output_items[0][:] = input_items[0] * self.multiplier return len(output_items[0])'''
name = create_embedded_python_block(source_code=source)# Returns: "epy_block_0"
# With custom namename = create_embedded_python_block( source_code=source, block_name="multiplier")# Returns: "multiplier_0"Notes
- Embedded blocks must inherit from
gr.sync_block,gr.decim_block, orgr.interp_block - The block class must define
__init__andworkmethods - Use
set_block_params()to configure the block after creation