CKTIS / Python
cProfile.runctx
runctx profile des instructions avec un dictionnaire global et une table de noms locaux fournis.
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
cProfile.runctx(statement, globals, locals, filename=None, sort=-1)runctx profile des instructions avec un dictionnaire global et une table de noms locaux fournis.
Dans CPython 3.14.9, raise SystemExit() dans ce contexte fait renvoyer None par runctx, tandis que raise ValueError() propage l’exception. Dans les deux cas le profil est écrit dans le fichier indiqué et reste lisible par pstats.Stats. Comme avec exec, une affectation simple au premier niveau écrit dans locals. Dans l’exemple, n vaut 4 et local['total'] contient ensuite 12. Avec filename le profil est enregistré, sinon un rapport ordonné selon sort est affiché.
La fonction renvoie 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
Exemples
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())
Résultat
12 True
La fonction renvoie None.