Skip to content

Commit 338e784

Browse files
committed
Fix --outfile when the program being profiled changes the working directory
1 parent 6e8128f commit 338e784

File tree

4 files changed

+27
-1
lines changed

4 files changed

+27
-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
@@ -7,7 +7,7 @@
77
from difflib import unified_diff
88
from io import StringIO
99
from test.support import run_unittest
10-
from test.support.os_helper import TESTFN, unlink
10+
from test.support.os_helper import TESTFN, unlink, temp_dir, change_cwd
1111
from contextlib import contextmanager
1212

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

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

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

0 commit comments

Comments
 (0)