Overview
The Very High Level Layer provides simple functions to execute Python code from C without detailed interaction with the interpreter. These functions accept Python source code as strings or files.Running Python Code
From Strings
PyRun_SimpleString
__main__ module.
const char*
required
Python source code to execute
0 on success, -1 if an exception was raised
Example:
Unhandled
SystemExit exceptions will exit the process (unless PyConfig.inspect is set).From Files
PyRun_SimpleFile
FILE*
required
Open file pointer to read Python code from
const char*
required
Filename for error messages (decoded from filesystem encoding)
0 on success, -1 on error
Example:
Interactive Execution
PyRun_InteractiveOne
FILE*
required
Interactive input source (typically stdin)
const char*
required
Filename for prompts and error messages
0- Input executed successfully-1- An exception occurred- Error code from
errcode.h- Parse error
sys.ps1 and sys.ps2.
PyRun_InteractiveLoop
0 at EOF, negative on failure
Example:
Advanced Execution
PyRun_String
const char*
required
Python source code to compile and execute
int
required
Grammar start symbol (see Start Symbols below)
PyObject*
required
Global namespace dictionary
PyObject*
required
Local namespace (can be any mapping object)
PyObject*, or NULL on error
Example:
Compilation
Py_CompileString
const char*
required
Python source code
const char*
required
Filename for error messages and tracebacks
int
required
Start symbol:
Py_file_input, Py_eval_input, or Py_single_inputNULL on error
Example:
PyEval_EvalCode
PyObject*
required
Code object from
Py_CompileStringPyObject*
required
Global namespace dictionary
PyObject*
required
Local namespace dictionary
Start Symbols
Start symbols determine what kind of Python code can be compiled:int
Single expression - returns the expression value
int
Sequence of statements - typical for modules/files
int
Single statement - used in interactive interpreters
int
Function type annotation - requires
PyCF_ONLY_AST flagUsed for parsing PEP 484 signature type comments.Compiler Flags
Control compilation behavior withPyCompilerFlags:
Common Flags
PyCF_ALLOW_TOP_LEVEL_AWAIT- Allowawaitat module levelPyCF_ONLY_AST- Return AST instead of code objectPyCF_TYPE_COMMENTS- Enable PEP 484 type comments
Input Hooks
Customize interactive input behavior:PyOS_InputHook
PyOS_ReadlineFunctionPointer
See Also
Introduction
C API basics and setup
Import Modules
Import and use Python modules
Exception Handling
Handle execution errors
Utilities
Argument parsing and utilities
