CKTIS / Python
cProfile.runctx
runctx profileert opdrachten met het opgegeven globale woordenboek en de lokale naamtoewijzing.
Versie: Python 3.14; repository image, production runtime not attested
Syntax
cProfile.runctx(statement, globals, locals, filename=None, sort=-1)runctx profileert opdrachten met het opgegeven globale woordenboek en de lokale naamtoewijzing.
In CPython 3.14.9 laat raise SystemExit() in deze context runctx eindigen met None, terwijl raise ValueError() de uitzondering doorgeeft. In beide gevallen komt het profiel in het opgegeven bestand en kan pstats.Stats het lezen. Net als bij exec schrijft een gewone toekenning op het hoogste niveau naar locals. In het voorbeeld is n gelijk aan 4 en bevat local['total'] daarna 12. Met filename wordt het profiel opgeslagen, anders verschijnt een volgens sort geordend verslag.
De functie geeft 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
Voorbeelden
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())
Resultaat
12 True
De functie geeft None.