Skip to content

Commit 7c94902

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 e5c7ac7 commit 7c94902

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
@@ -152,6 +152,11 @@ def main():
152152
(options, args) = parser.parse_args()
153153
sys.argv[:] = args
154154

155+
# The script that we're profiling may chdir, so capture the absolute path
156+
# to the output file at startup.
157+
if options.outfile is not None:
158+
options.outfile = os.path.abspath(options.outfile)
159+
155160
if len(args) > 0:
156161
if options.module:
157162
code = "run_module(modname, run_name='__main__')"

Lib/profile.py

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

574+
# The script that we're profiling may chdir, so capture the absolute path
575+
# to the output file at startup.
576+
if options.outfile is not None:
577+
options.outfile = os.path.abspath(options.outfile)
578+
574579
if len(args) > 0:
575580
if options.module:
576581
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)