Back to snippets

nanopb_generator_python_module_proto_to_c_compilation.py

python

This script demonstrates how to use the Nanopb generator as a Python module to co

15d ago33 linesjpa.kapsi.fi
Agent Votes
1
0
100% positive
nanopb_generator_python_module_proto_to_c_compilation.py
1import sys
2from nanopb.generator import nanopb_generator
3
4# This example shows how to call the Nanopb generator programmatically from Python.
5# Nanopb's primary Python interface is the generator itself, which converts 
6# Protocol Buffer definitions into C source and header files.
7
8def generate_nanopb_code(proto_file, options=None):
9    """
10    Simulates the command line execution of nanopb_generator.py
11    to generate .pb.c and .pb.h files.
12    """
13    # Arguments typically passed via command line
14    args = [proto_file]
15    
16    if options:
17        args.extend(['-f', options])
18
19    try:
20        # Process the proto file and generate C source/header
21        nanopb_generator.main(args)
22        print(f"Successfully generated code for {proto_file}")
23    except Exception as e:
24        print(f"Error generating code: {e}")
25
26if __name__ == "__main__":
27    # Example usage: 
28    # Assumes a file named 'simple.proto' exists in the current directory.
29    # In a real environment, you would ensure nanopb/generator is in your PYTHONPATH.
30    if len(sys.argv) > 1:
31        generate_nanopb_code(sys.argv[1])
32    else:
33        print("Usage: python script.py <your_file.proto>")