Skip to content

Commit 1c5a657

Browse files
authored
bpo-40492: Fix --outfile with relative path when the program changes it working dir (GH-19910)
(cherry picked from commit 3c0ac18)
1 parent 1a3f7c0 commit 1c5a657

File tree

4 files changed

+28
-1
lines changed

4 files changed

+28
-1
lines changed

Lib/cProfile.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,11 @@ def main():
168168
(options, args) = parser.parse_args()
169169
sys.argv[:] = args
170170

171+
# The script that we're profiling may chdir, so capture the absolute path
172+
# to the output file at startup.
173+
if options.outfile is not None:
174+
options.outfile = os.path.abspath(options.outfile)
175+
171176
if len(args) > 0:
172177
if options.module:
173178
code = "run_module(modname, run_name='__main__')"

Lib/profile.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,11 @@ def main():
587587
(options, args) = parser.parse_args()
588588
sys.argv[:] = args
589589

590+
# The script that we're profiling may chdir, so capture the absolute path
591+
# to the output file at startup.
592+
if options.outfile is not None:
593+
options.outfile = os.path.abspath(options.outfile)
594+
590595
if len(args) > 0:
591596
if options.module:
592597
import runpy

Lib/test/test_profile.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import os
77
from difflib import unified_diff
88
from io import StringIO
9-
from test.support import TESTFN, run_unittest, unlink
9+
from test.support import TESTFN, run_unittest, unlink, temp_dir, change_cwd
1010
from contextlib import contextmanager
1111

1212
import profile
@@ -111,6 +111,20 @@ def test_run_profile_as_module(self):
111111
assert_python_ok('-m', self.profilermodule.__name__,
112112
'-m', 'timeit', '-n', '1')
113113

114+
def test_output_file_when_changing_directory(self):
115+
with temp_dir() as tmpdir, change_cwd(tmpdir):
116+
os.mkdir('dest')
117+
with open('demo.py', 'w') as f:
118+
f.write('import os; os.chdir("dest")')
119+
120+
assert_python_ok(
121+
'-m', self.profilermodule.__name__,
122+
'-o', 'out.pstats',
123+
'demo.py',
124+
)
125+
126+
self.assertTrue(os.path.exists('out.pstats'))
127+
114128

115129
def regenerate_expected_output(filename, cls):
116130
filename = filename.rstrip('co')
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix ``--outfile`` for :mod:`cProfile` / :mod:`profile` not writing the output
2+
file in the original directory when the program being profiled changes the
3+
working directory. PR by Anthony Sottile.

0 commit comments

Comments
 (0)