Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Lib/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ def main():
if len(args) > 0:
if options.module:
import runpy
code = "run_module(modname, run_name='__main__')"
code = "run_module(modname, run_name='__main__', alter_sys=True)"
globs = {
'run_module': runpy.run_module,
'modname': args[0]
Expand Down
2 changes: 1 addition & 1 deletion Lib/profiling/tracing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def main():

if len(args) > 0:
if options.module:
code = "run_module(modname, run_name='__main__')"
code = "run_module(modname, run_name='__main__', alter_sys=True)"
globs = {
'run_module': runpy.run_module,
'modname': args[0]
Expand Down
21 changes: 20 additions & 1 deletion Lib/test/test_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pstats
import unittest
import os
import textwrap
import warnings
from difflib import unified_diff
from io import StringIO
Expand All @@ -15,7 +16,8 @@
warnings.simplefilter("ignore", DeprecationWarning)
import profile
from test.profilee import testfunc, timer
from test.support.script_helper import assert_python_failure, assert_python_ok
from test.support.script_helper import (
assert_python_failure, assert_python_ok, make_script)


class ProfileTest(unittest.TestCase):
Expand Down Expand Up @@ -120,6 +122,23 @@ def test_run_profile_as_module(self):
assert_python_ok('-m', self.profilermodule.__name__,
'-m', 'timeit', '-n', '1')

def test_profile_module_as_main(self):
# The module must run as __main__, like with "python -m module".
with temp_dir() as tmpdir:
make_script(tmpdir, 'profiled_module', textwrap.dedent("""\
import pickle
import sys

class Foo:
pass

assert sys.modules['__main__'].Foo is Foo
assert sys.argv[0].endswith('profiled_module.py')
pickle.dumps(Foo())
"""))
assert_python_ok('-m', self.profilermodule.__name__,
'-m', 'profiled_module', PYTHONPATH=tmpdir)

def test_output_file_when_changing_directory(self):
with temp_dir() as tmpdir, change_cwd(tmpdir):
os.mkdir('dest')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Fix :mod:`cProfile` and :mod:`profile` when profiling a module with the
``-m`` option: the module now runs as ``__main__`` and ``sys.argv[0]`` is
set to its path, as with ``python -m``. This fixes errors when pickling
objects defined in the module, for example when using :mod:`multiprocessing`
with the ``spawn`` start method.
Loading