Description
Bug report
Bug description:
Starting in 3.12 with the addition of sys.monitoring, _lsprof, specifically in profiler_enable, no longer calls _PyEval_SetProfile.
Very specifically, this impacts previous functionality where python -m cProfile -m whatever would result in sys.setprofile() being called, and subsequently the whatever module could access the profiler object via sys.getprofile()
To my knowledge this is now completely impossible as sys.monitoring provides no meaningful way to access the profiler object.
In my particular use case, profiling could be enabled within the application, or if python -m cProfile was used, the existing profiler could be used allowing profiling to happen earlier than the enablement point of cProfile within the application.
Something to the effect of:
p = sys.getprofile()
if p is None:
p = cProfile.Profile()
p.enable()CPython versions tested on:
3.13
Operating systems tested on:
Linux
Activity
gaogaotiantian commentedon Feb 20, 2025
This is not a bug.
sys.getprofilegets the profile function fromsys.setprofile,cProfilebefore 3.12 happened to use that specific utility for profiling. It switched tosys.monitoringmechanism after 3.12, sosys.getprofilewon't get anything forcProfile. Yes they both have the wordprofilein it, but there's never a guarantee that they will always be related.cProfiledocumentation does not provide a way to get the profile object from CLI either. This is just something unsupported that happened to work before 3.12.If you just want something equivalent to your current method (which is not 100% accurate, it's only guarantees that if
cProfileis running,sys.getprofile()will be notNone), you can dosys.monitoring.get_tool(sys.monitoring.PROFILER_ID)- that will return a string if cProfile is running.Still, cProfile does not provide an official way to access it's profiler object in CLI mode, if you need that, that's a feature request.
BHUVANSH855 commentedon Oct 20, 2026
this came from PR #103534 which quietly removed the test assertions checking
sys.getprofile() == profwith no changelog note.The real gap is that
get_tool()gives you a string but no way to reach the object.Since PEP 799 is accepted and
profiling.tracinglands in 3.15, a small addition makes sense:use_tool_idalready guarantees one owner, so the object is right there in_lsprof. Worth a feature request againstprofiling.tracing.@gaogaotiantian @pablogsal, happy to draft a PR.