Skip to main content

Python/pythonrun.c

cpython 3.14 @ ab2d84fe1023/Python/pythonrun.c

Python/pythonrun.c implements the high-level "compile and run" entry points declared in Include/pythonrun.h. It bridges the compile pipeline (Python/compile.c) and the eval loop (Python/ceval.c) and handles the interactive REPL loop.

Map

LinesSymbolRole
1-200run_eval_code_objExecute a code object in a namespace
201-450PyRun_SimpleStringFlagsCompile + run a string in __main__
451-700PyRun_FileExFlagsRead + compile + run a file
701-950run_modCompile AST to code object and run
951-1200PyRun_InteractiveLoopFlagsREPL: read one statement, compile, run, repeat
1201-1400parse_syntax_errorExtract SyntaxError fields for display

Reading

run_eval_code_obj

The lowest-level helper: takes an already-compiled code object and runs it.

// CPython: Python/pythonrun.c:85 run_eval_code_obj
static PyObject *
run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co,
PyObject *globals, PyObject *locals)
{
...
return PyEval_EvalCode((PyObject *)co, globals, locals);
}

run_mod compile + run

run_mod takes a parsed AST node, compiles it with PyAST_CompileObject, and calls run_eval_code_obj. The optimize flag from PyConfig controls constant folding in the compiler.

// CPython: Python/pythonrun.c:900 run_mod
static PyObject *
run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
PyCompilerFlags *flags, PyArena *arena, PyObject *interactive_src,
int optimize)
{
PyCodeObject *co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
if (co == NULL) return NULL;
return run_eval_code_obj(tstate, co, globals, locals);
}

Interactive loop

PyRun_InteractiveLoopFlags reads one logical statement at a time from sys.stdin using PyOS_Readline. Each statement is compiled with Py_single_input start token, which causes the result of an expression statement to be printed via sys.displayhook.

gopy notes

pythonrun/runstring.go mirrors PyRun_SimpleStringFlags. The compile+eval pipeline calls compile.Compile then vm.Eval. The interactive loop is not yet implemented.