mirror of
https://github.com/pocketpy/pocketpy
synced 2025-10-24 05:20:17 +00:00
2.4 KiB
2.4 KiB
| icon | label | order |
|---|---|---|
| dot | Execute Python Code | 93 |
Simple execution
Once you have a VM instance, you can execute python code by calling exec method.
PyVar exec(Str source, Str filename, CompileMode mode, PyVar _module=nullptr)
source, the python source code to be executedfilename, the filename of the source code. This is used for error reportingmode, the compile mode. See below for detailsmodule, the module where the code will be executed. Ifnullptr, the code will be executed in the__main__module
exec handles possible exceptions and returns a PyVar.
If the execution is not successful, e.g. a syntax error or a runtime exception,
the return value will be nullptr.
There are also overloaded versions of exec and eval, which is useful for simple execution:
PyVar exec(Str source)PyVar eval(Str source)
Compile mode
The mode parameter controls how the source code is compiled. There are 5 possible values:
EXEC_MODE, this is the default mode. Just do normal execution.EVAL_MODE, this mode is used for evaluating a single expression. Thesourceshould be a single expression. It cannot contain any statements.REPL_MODE, this mode is used for REPL. It is similar toEXEC_MODE, but generatesPRINT_EXPRopcode when necessary.CELL_MODE, this mode is designed for Jupyter like execution. It is similar toEXEC_MODE, but generatesPRINT_EXPRopcode when necessary.JSON_MODE, this mode is used for JSON parsing. It is similar toEVAL_MODE, but uses a lexing rule designed for JSON.
Fine-grained execution
In some cases, you may want to execute python code in a more fine-grained way. These two methods are provided for this purpose:
CodeObject_ compile(Str source, Str filename, CompileMode mode, bool unknown_global_scope)PyVar _exec(CodeObject_ co, PyVar _module)
compilecompiles the source code into aCodeObject_instance. Leaveunknown_global_scopetofalseif you don't know what it means._execexecutes theCodeObject_instance.
!!!
_exec does not handle exceptions, you need to use try..catch manually.
!!!
try{
CodeObject_ code = vm->compile("a[0]", "main.py", EXEC_MODE, false);
vm->_exec(code, vm->_main);
}catch(Exception& e){
// use e.summary() to get a summary of the exception
std::cerr << e.summary() << std::endl;
}