Skip to content

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

NameTypeDefaultDescription
output_dirstr""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 warnings
result = 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_options in 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

NameTypeDefaultDescription
exprstr-Python expression to evaluate

Returns

Type: Any

Result of the expression evaluation.

Example

101300000.0
# Arithmetic
result = evaluate_expression("101.1e6 + 200e3")
# Using numpy (available in flowgraph namespace)
result = evaluate_expression("np.pi * 2")
# Returns: 6.283185307179586
# Complex expressions
result = evaluate_expression("int(2e6 / 10)")
# Returns: 200000

create_embedded_python_block

Create an embedded Python block from source code.

Parameters

NameTypeDefaultDescription
source_codestr-Python source code for the block
block_namestr | NoneNoneOptional custom block name

Returns

Type: str

The assigned block name.

Example

source = '''
import numpy as np
from 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 name
name = 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, or gr.interp_block
  • The block class must define __init__ and work methods
  • Use set_block_params() to configure the block after creation