Skip to content

gh-158985: Make profile and cProfile -m run the module as __main__ - #158992

Open
sricursion wants to merge 1 commit into
python:mainfrom
sricursion:profile-module-run-as-main
Open

sricursion wants to merge 1 commit into
python:mainfrom
sricursion:profile-module-run-as-main

Conversation

@sricursion

@sricursion sricursion commented Oct 7, 2026 •

Copy link
Copy Markdown

python -m cProfile -m MODULE and python -m profile -m MODULE run the module with runpy.run_module() and its default alter_sys=False, so sys.modules['__main__'] stays the profiler module and sys.argv[0] is the bare module name. Objects defined in the profiled module then cannot be pickled, which breaks ProcessPoolExecutor and multiprocessing with the spawn start method. Profiling a script path was fixed in gh-132737 and gh-140729, but the -m branch was not changed. This passes alter_sys=True in profile.main() and profiling.tracing.main(), so the module runs as __main__ with sys.argv[0] set to its path, as under python -m. The regression test is added to ProfileTest, so it also runs for profiling.tracing through CProfileTest.

Pass alter_sys=True to runpy.run_module() in the -m branch of profile
and profiling.tracing, so that sys.modules['__main__'] and sys.argv[0]
refer to the profiled module, as with python -m.
@sricursion
sricursion requested a review from pablogsal as a code owner October 7, 2026 20:27
@python-cla-bot

python-cla-bot Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant