WissensdatenbankPrüfungszentrum
DEDeutsch
Sprache wählen13

CKTIS / Python

cProfile.runctx

runctx profiliert Anweisungen mit einem globalen Wörterbuch und einer lokalen Namenszuordnung.

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

Syntax

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

runctx profiliert Anweisungen mit einem globalen Wörterbuch und einer lokalen Namenszuordnung.

In CPython 3.14.9 beendet raise SystemExit() in diesem Kontext runctx mit None, während raise ValueError() den Fehler weitergibt. In beiden Fällen landet das Profil in der angegebenen Datei und kann mit pstats.Stats gelesen werden. Wie bei exec landet eine einfache Zuweisung auf oberster Ebene in locals. Im Beispiel ist n gleich 4, anschließend enthält local['total'] den Wert 12. Mit filename wird das Profil gespeichert, ohne Dateinamen erscheint ein nach sort geordneter Bericht.

Die Funktion liefert None.

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

Beispiele

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())

Ergebnis

12 True

Die Funktion liefert None.

Quellen