Access Python Variables and Objects from SystemVerilog

Code snippet demonstrates how access Python variables and Objects from SystemVerilog simulation. PyStim initializes the Python interpreter, sets variables, executes Python code, retrieves results, and displays them, enabling the use of Python’s computational capabilities alongside SystemVerilog’s hardware modeling features.

import pystim_pkg::*;

module set_get_vars();
    typedef pystim py;

    initial begin
        py::initialize_interpreter();
        begin
            automatic py_dict globals = py::globals();
            automatic py_dict locals = py_dict::create_empty();
            automatic py_int res;

            locals.set(py::str_("a"), py::int_(5));

            py::exec("mult_res = a * 4", globals, locals);
            res = locals.get(py::str_("mult_res")).cast_int();

            $display("The result of multiplying a by 4 is: %0d", res.get_value());
        end
        py::finalize_interpreter();
    end
    
endmodule

The exec method returns the execution status. If a Python code execution error occurs, it will return an instance of the py_error class, which contains details of the Python exception. Otherwise, it will return an object of type py_none.

It’s a good idea to check the execution status before proceeding. You can also enable Python exception printing and halt the SystemVerilog simulation if a Python exception occurs.