Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

cProfile.runctx

Profiles trusted statement text with explicit global and local namespaces.

Version: Python 3.14; repository image, production runtime not attested

Syntax

cProfile.runctx(statement, globals, locals, filename=None, sort=-1)

Profiles trusted statement text with explicit global and local namespaces.

Assignments made by the statement are observable in the supplied local mapping. Profile timings can be stored separately from the calculated result.

The statement executes with exec semantics in the supplied global dictionary and local mapping. A top-level assignment goes into locals. Omitting filename prints a report ordered by sort. A filename stores profiling data instead. Here the calculated 12 is read from local and the file exists. In CPython 3.14.9, raise SystemExit() in that context makes runctx return None, whereas raise ValueError() propagates. Both paths save a readable stats dump when given a filename.

import cProfile,pstats,tempfile,os
g={'scale':3}
l={'n':4}
with tempfile.TemporaryDirectory() as directory:
    path=os.path.join(directory,'t.prof')
    assert cProfile.runctx("total = n*scale",g,l,path) is None
    assert l['total']==12 and 'total' not in g
    assert pstats.Stats(path).total_calls>0
with tempfile.TemporaryDirectory() as directory:
    for exc in ('SystemExit','ValueError'):
        path=os.path.join(directory,exc+'.prof')
        try: result=cProfile.runctx("raise "+exc+"()",g,l,path)
        except ValueError: assert exc=='ValueError'
        else: assert exc=='SystemExit' and result is None
        assert pstats.Stats(path).total_calls>0

Examples

import cProfile
from pathlib import Path
from tempfile import TemporaryDirectory

local = {"n": 4}
with TemporaryDirectory() as d:
    p = Path(d) / "sample.prof"
    cProfile.runctx("total = n * 3", {}, local, str(p))
    print(local["total"], p.is_file())

Result

12 True

The statement executes with exec semantics in the supplied global dictionary and local mapping. A top-level assignment goes into locals. Omitting filename prints a report ordered by sort. A filename stores profiling data instead. Here the calculated 12 is read from local and the file exists. In CPython 3.14.9, raise SystemExit() in that context makes runctx return None, whereas raise ValueError() propagates. Both paths save a readable stats dump when given a filename.

Sources