Skip to content

[3.9] bpo-40492: Fix --outfile with relative path when the program changes it working dir (GH-19910) #22752

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 18, 2020
Merged
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
5 changes: 5 additions & 0 deletions Lib/cProfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,11 @@ def main():
(options, args) = parser.parse_args()
sys.argv[:] = args

# The script that we're profiling may chdir, so capture the absolute path
# to the output file at startup.
if options.outfile is not None:
options.outfile = os.path.abspath(options.outfile)

if len(args) > 0:
if options.module:
code = "run_module(modname, run_name='__main__')"
Expand Down
5 changes: 5 additions & 0 deletions Lib/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,11 @@ def main():
(options, args) = parser.parse_args()
sys.argv[:] = args

# The script that we're profiling may chdir, so capture the absolute path
# to the output file at startup.
if options.outfile is not None:
options.outfile = os.path.abspath(options.outfile)

if len(args) > 0:
if options.module:
import runpy
Expand Down
16 changes: 15 additions & 1 deletion Lib/test/test_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import os
from difflib import unified_diff
from io import StringIO
from test.support import TESTFN, run_unittest, unlink
from test.support import TESTFN, run_unittest, unlink, temp_dir, change_cwd
from contextlib import contextmanager

import profile
Expand Down Expand Up @@ -111,6 +111,20 @@ def test_run_profile_as_module(self):
assert_python_ok('-m', self.profilermodule.__name__,
'-m', 'timeit', '-n', '1')

def test_output_file_when_changing_directory(self):
with temp_dir() as tmpdir, change_cwd(tmpdir):
os.mkdir('dest')
with open('demo.py', 'w') as f:
f.write('import os; os.chdir("dest")')

assert_python_ok(
'-m', self.profilermodule.__name__,
'-o', 'out.pstats',
'demo.py',
)

self.assertTrue(os.path.exists('out.pstats'))


def regenerate_expected_output(filename, cls):
filename = filename.rstrip('co')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix ``--outfile`` for :mod:`cProfile` / :mod:`profile` not writing the output
file in the original directory when the program being profiled changes the
working directory. PR by Anthony Sottile.