diff --git a/Lib/cProfile.py b/Lib/cProfile.py index e7c868b8d55543..8503ccbe57f83c 100644 --- a/Lib/cProfile.py +++ b/Lib/cProfile.py @@ -6,6 +6,7 @@ import _lsprof import importlib.machinery +import importlib.util import io import profile as _pyprofile @@ -169,17 +170,22 @@ def main(): else: progname = args[0] sys.path.insert(0, os.path.dirname(progname)) - with io.open_code(progname) as fp: - code = compile(fp.read(), progname, 'exec') spec = importlib.machinery.ModuleSpec(name='__main__', loader=None, origin=progname) + loader = importlib.machinery.SourceFileLoader("__main__", progname) + spec.loader = loader + module = importlib.util.module_from_spec(spec) globs = { '__spec__': spec, '__file__': spec.origin, '__name__': spec.name, '__package__': None, '__cached__': None, + 'module': module } + + sys.modules["__main__"] = module + code = "__spec__.loader.exec_module(module)" try: runctx(code, globs, None, options.outfile, options.sort) except BrokenPipeError as exc: diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-04-19-18-07-34.gh-issue-132737.9mW1il.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-19-18-07-34.gh-issue-132737.9mW1il.rst new file mode 100644 index 00000000000000..5bdd54a3fbae17 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-04-19-18-07-34.gh-issue-132737.9mW1il.rst @@ -0,0 +1 @@ +Support profiling modules that import __main___, such as modules that use to pickle. The github issue has an example repro that throws an exception without this change, and succeeds with it.